Load js Asynchronously But Execute Synchronously

这一生的挚爱 提交于 2021-02-07 03:06:47

问题


The Scenario is that I have lots of js files. Different files are called depending on different platforms. So I have a question as I want to load files Asynchronously. But the Execution of these files should be done synchronously. Currently I am doing this function call

  function loadScriptJs(src) {   
     Console.log(' Call to file '+src);
     var file = document.createElement('script'),
            head = document.getElementsByTagName('head')[0];
    file.type = 'text/javascript';
    file.setAttribute("defer","defer");
    file.setAttribute("src",src);
    head.appendChild(file);
        file.onload = function() {            
              console.log(src + " is loaded.");
        };
  }

Now I have a array which has a list of js files being called. I loop through the array and call this function for each src. I have used document.ready function with in each of the js file. Here I have checked the dependencies of the files and made the sequence optimized. ie The dependent files are loaded later (come later in the array) and the more Parent like files come earlier.

Example:- If I have files A1,B2,C3,D4,E5 ..... like wise. My array is ['js/A1.js','js/B2.js','js/C3.js'...]. When I run this through the loop. I get the consoles of 'Call to file [filename]' is the same sequence as in the array but consoles of '[filename] is loaded' are not coming in the intended sequence.

Yes I cannot control the loading as its over the internet. But I want to the execution to be synchronous. ie Begin all file execution when the last file completes loading.

Can anyone provide me any advice, suggestion or idea for it.


回答1:


Dynamically inserted scripts may not adhere to the defer attribute. script tags have an async attribute. By default it's true. Explicitly set it to false.

file.setAttribute("async", "false");

or in plain HTML

<script type="text/javascript" async=false src="A1.js"></script>

You might also need to remove the document.ready method in each script and start the script's logic at the top level, appending each JS script to the bottom of the body tag instead of the header. If multiple scripts register for the ready event before it's fired you do not know what order they will be called in.



来源:https://stackoverflow.com/questions/23908750/load-js-asynchronously-but-execute-synchronously

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!