Question

I'm trying out Ryan Fioravanti's neat-o technique for deferring JavaScript execution. It's described in slide 27 and slide 28 of his presentation at Google I/O.

In WebKit browsers, it works great, providing measurably better results than just putting the script tag at the bottom of the page or using the async attribute.

However, it does not work in Firefox or IE. I can see in Firebug that the script gets inserted into the DOM but I can also see in Firebug that the script itself is never executed.

The problem appears for both external scripts like <script src="..."></script> and inline scripts like <script>//inline code goes here</script>.

Has anyone gotten this technique to work in non-WebKit browsers?

Here's the relevant source code to replicate the issue:

<script type="text/notJs">
    alert('This alert will show in Chrome and Safari thanks to the DOM manipulation below! But it does not show in Firefox or IE.');
</script>
<script>
    window.onload = function () {
        var scripts = document.getElementsByTagName('script');
        var scriptIndex = 0;
        for (var i = 0, len = scripts.length; i < len; i++) {
            var scriptEl = scripts[scriptIndex];
            if (scriptEl.type === 'text/notJs') {
                scriptEl.type = 'text/javascript';
                scriptEl.parentNode.removeChild(scriptEl);
                document.body.appendChild(scriptEl);
            } else {
                scriptIndex++;
            }
        }
    };
</script>
Was it helpful?

Solution

Here's code that seems to work in Firefox, IE, Safari, and Chrome. It works for both inline scripts and external scripts.

<script>
    window.onload = function () {
        var scripts = document.getElementsByTagName('script'),
            scriptIndex = 0,
            newScript,
            scriptEl;
        for (var i = 0, len = scripts.length; i < len; i++) {
            scriptEl = scripts[scriptIndex];
            if (scriptEl.type === 'text/notJs') {
                scriptEl.parentNode.removeChild(scriptEl);
                newScript = document.createElement('script');
                newScript.type = "text/javascript";
                if (scriptEl.text) {
                    newScript.text = scriptEl.text;
                } else {
                    newScript.src = scriptEl.src;
                }
                document.body.appendChild(newScript);
            } else {
                scriptIndex++;
            }
        }
    };
</script>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top