Js loading USES the DOM method to load Javascript files dynamically

  • 2020-03-26 23:47:41
  • OfStack

Traditionally, Javascript files are loaded using < Script> The label.
Like this:
< The script type = "text/javascript" SRC = "example. Js >" < / script>
< img SRC = "border = 0 / / files.jb51.net/file_images/article/201311/201311081149442.gif? 201310811502 ">  
< Script> Tags are easy to add to a web page and the browser will read and run them. But it has some serious flaws.
(1) strict reading order. As browsers follow < Script> The order in which Javascript files appear in a web page, read from them, and then run immediately results in a situation where multiple files are dependent on each other, the least dependent files must be placed first, and the most dependent files must be placed last, or the code will report an error.
(2) performance problems. Browsers load in "synchronous mode". Script> The TAB, that is, the page is "blocked," waiting for the javascript file to load before running the HTML code. When there are multiple < Script> When tags are read, the browser cannot read them at the same time, so it has to read one and then read the other, resulting in much longer reading time and slow page response.
To solve these problems, you can use the DOM method to load Javascript files dynamically.
  function loadScript(url){ 
    var script = document.createElement("script"); 
    script.type = "text/javascript"; 
    script.src = url; 

The way this works is that the browser creates a < Script> Tag, and then "asynchronously" read the Javascript file. This doesn't cause page congestion, but it does cause another problem: the Javascript file that is loaded this way is not in the original DOM structure, so the callback function specified in the dom-ready (DOMContentLoaded) event and the window.onload event is not valid for it.

Related articles: