简体   繁体   English

Javascript数组推迟JS加载Joomla

[英]Javascript array to defer js loading joomla

I am deferring the loading of some js files in my Joomla template. 我推迟了Joomla模板中某些js文件的加载。 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. 但是,我有大约12个这样的js文件要加载,对于每个文件我都必须使用与上述相同的代码块,只是pathto.js不同。

My Javascript abilities are pretty rubbish. 我的Javascript能力很垃圾。 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? 是否可以将所有js文件放入一个数组,然后使用相同的代码块一个接一个地遍历它们,而不必一遍又一遍地重复相同的块?

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! 感谢您对此的任何帮助!

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);
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM