← Will Donnelly

This is fairly niche, but it's kind of a fun little trick. Suppose that you've to implemented an interpreter for some language running inside a web browser, and you want to support script tags for that language.

Simply register a listener for DOMContentLoaded in which you iterate over all script elements with the appropriate type attribute. If a src attribute is specified then fetch that and execute the result, otherwise execute the contents of the script element:

// ===================== //
// ===================== //
(function () {
    const SCRIPT_LANGUAGE_NAME = 'brainfuck';
    const SCRIPT_TAG_TYPE = 'text/brainfuck';
    const SCRIPT_EXECUTE = ExecuteBrainfuck;

    // Make sure this setup code only ever runs once
    if (!window.scriptLanguages) { window.scriptLanguages = {}; }
    if (window.scriptLanguages[SCRIPT_LANGUAGE_NAME]) { return; }
    window.scriptLanguages[SCRIPT_LANGUAGE_NAME] = true;

    document.addEventListener('DOMContentLoaded', async function () {
        console.log("Locating and Executing Scripts of Type", SCRIPT_TAG_TYPE);
        var scripts = document.getElementsByTagName('script');
        for (var i = 0; i < scripts.length; i++) {
            if (scripts[i].type == SCRIPT_TAG_TYPE) {
                if (scripts[i].src) {
                    console.log('Executing Script:', scripts[i].src);
                    const response = await fetch(scripts[i].src);
                    if (!response.ok) {
                        console.error('Unable to fetch script', scripts[i].src);
                        throw new Error(`unable to fetch script '${scripts[i].src}'`);
                    const code = await response.text();
                    await SCRIPT_EXECUTE(code);
                } else {
                    console.log('Executing Script:', scripts[i].text);
                    await SCRIPT_EXECUTE(scripts[i].text);
For a full example, see: brainfuck.html.