Home  >  Article  >  Web Front-end  >  js loading uses DOM method to dynamically load Javascript files

js loading uses DOM method to dynamically load Javascript files

高洛峰
高洛峰Original
2017-02-06 09:28:291286browse

Traditionally, loading Javascript files uses the 3f1c4e4b6b16bbbd69b2ee476dc4f83a tag.
Like the following:
559853b309d71af2b7cfa1cfce4f8bd02cacc6d41bbb37262a98f745aa00fbf0

3f1c4e4b6b16bbbd69b2ee476dc4f83aThe tag is very convenient, as long as Add a web page and the browser will read it and run it. However, it has some serious flaws.
 (1) Strict reading order. Since the browser reads Javascript files in the order in which 3f1c4e4b6b16bbbd69b2ee476dc4f83a appears in the web page, and then runs them immediately, when multiple files depend on each other, the file with the least dependency must be placed first, and the one with the greatest dependency must be placed first. The file must be placed at the end, otherwise the code will report an error.
  (2) Performance issues. The browser uses "synchronous mode" to load the 3f1c4e4b6b16bbbd69b2ee476dc4f83a tag, which means that the page will be "blocked", waiting for the JavaScript file to be loaded before running the subsequent HTML code. When there are multiple 3f1c4e4b6b16bbbd69b2ee476dc4f83a tags, the browser cannot read them at the same time. It must read one before reading the other, which causes the reading time to be greatly extended and the page response to be slow.
In order to solve these problems, you can use the DOM method to dynamically load Javascript files.

  function loadScript(url){ 
    var script = document.createElement("script"); 
    script.type = "text/javascript"; 
    script.src = url; 
    document.body.appendChild(script); 
  }

The principle of this is that the browser instantly creates a 3f1c4e4b6b16bbbd69b2ee476dc4f83a tag, and then reads the Javascript file "asynchronously". This will not cause page blocking, but it will cause another problem: the Javascript file loaded in this way is not in the original DOM structure, so the callback functions specified in the DOM-ready (DOMContentLoaded) event and window.onload event are invalid for it. .

For more js loading related articles on using DOM method to dynamically load Javascript files, please pay attention to the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn