Javascript array to defer js loading joomla

441 views Asked by At

I am deferring the loading of some js files in my Joomla template. This works fine

    <script type="text/javascript">
        function downloadJSAtOnload() {
            var element = document.createElement("script");
            element.src = "/pathto.js";
            document.body.appendChild(element);
        }
        if (window.addEventListener)
            window.addEventListener("load", downloadJSAtOnload, false);
        else if (window.attachEvent)
            window.attachEvent("onload", downloadJSAtOnload);
        else window.onload = downloadJSAtOnload;
    </script>

However, I have about a dozen js files to load like this and for each one I'm having to use the same block of code as above with just the pathto.js being different.

My Javascript abilities are pretty rubbish. Is it possible to put all the js files into an array and then just go through them one by one using the same block of code without having to repeat the same block over and over?

What I'd like is something like

    <script type="text/javascript">
        function downloadJSAtOnload() {
            var element = document.createElement("script");
            element.src = AN ARRAY OF JS FILES;
            document.body.appendChild(element);
        }
        FOR EACH ITEM IN THE ARRAY
            if (window.addEventListener)
                window.addEventListener("load", downloadJSAtOnload, false);
            else if (window.attachEvent)
                window.attachEvent("onload", downloadJSAtOnload);
            else window.onload = downloadJSAtOnload;
    </script>

Thanks for any help with this!

1

There are 1 answers

1
itoctopus On

Actually the loop should be in the function.

Here's what the function should be (I haven't tested it):

function downloadJSAtOnload() {
    var scripts = ["script1.js", "script2.js", "script3.js"];
    for (i = 0; i < scripts.length; i++) {
        var element = document.createElement("script");
        element.src = scripts[i];
        document.body.appendChild(element);
   }
}