Closed mourner closed 4 years ago
Tradeoffs :-)
I agree, the presentation and tooling would be better without this hack. The main reason I used it is that in some of my previous projects, I had duplicate code, one version that runs and one version that is displayed on the page. The main risk was that the version that's displayed (untested) can diverge from the version that runs (tested), and readers get the wrong version of the code.
Alternatives I considered for handling the duplication between the displayed code and the running code:
<pre>
, then run eval()
on it for the running version. That only helps with code highlighting and not with splitting code or linting. It seems similar enough to the current <script>
hack that I preferred the script hack (however I hadn't considered code highlighting).toString()
on the functions to extract the displayed code. I don't think toString()
is guaranteed to produce the same results across browsers, but I should look into that.Do you have a preference?
I looked at highlight.js and I can make it work on this page by running it on each of the <script>
elements:
document.querySelectorAll('main script:not([src])').forEach(element => {
let sibling = document.createElement('pre');
sibling.innerHTML = hljs.highlight('js', element.textContent, false, null).value;
element.parentNode.insertBefore(sibling, element);
});
However it doesn't solve lint or refactoring.
@redblobgames one more approach that I think would be relatively simple and keep all the benefits is to add a custom linting script that matches all the code in pre
blocks against the real code and fails the tests on a mismatch.
Also forgot to mention another potential drawback of the script hack — I have a suspicion that this code won't be indexed by search engines, although no proof of that.
@redblobgames I'm wondering whether we could drop the
script { display: block; }
hack — while it's definitely cool, it has some drawbacks: