JS load using the DOM method to dynamically load JavaScript files _javascript tips

Source: Internet
Author: User
Traditionally, loading JavaScript files is the use of <script> tags.
Just like the following:
<script type= "Text/javascript" src= "Example.js" ></script>

<script> tags are convenient, the browser will read and run as long as you join the Web page. However, it has some serious flaws.
(1) Strict reading order. Because browsers read JavaScript files in the order in which they appear in the Web page <script>, then run immediately, resulting in multiple files dependent on each other, the least dependent file must be placed at the front, the most dependent file must be on the last side, otherwise the code will complain.
(2) Performance problems. The browser uses "sync mode" to load <script> tag, that is, the page will "jam" (blocking), wait for the JavaScript file to load, and then run the following HTML code. When there are multiple <script> tags, the browser can not read at the same time, you must read one to read the other, resulting in a large reading time, slow page response.
To solve these problems, you can use the DOM method to dynamically load JavaScript files.
Copy Code code as follows:

function Loadscript (URL) {
var script = document.createelement ("script");
Script.type = "Text/javascript";
script.src = URL;
Document.body.appendChild (script);
}

The idea is that the browser creates a <script> tag instantly, and then "asynchronously" reads the JavaScript file. This does not cause the page to jam, but it creates another problem: the JavaScript file that is loaded is not in the original DOM structure, Therefore, the callback function specified in the Dom-ready (domcontentloaded) and window.onload events is not valid for it.
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.