Two Methods for dynamically loading script files

Source: Internet
Author: User

There are two ways to dynamically load scripts to pages:

The first method is to use ajax to load the script file code from the background to the foreground, and then run the code on the loaded content through eval. The second is to dynamically create a script tag, set its src attribute, and load js by inserting the script tag into the page head, it is equivalent to writing a <script src = "... "> </script>, but this script tag is dynamically created using js.
For example, if we want to dynamically load a callbakc. js file, we need such a script Tag:
Copy codeThe Code is as follows:
<Script type = "text/javascript" src = "call. js"> </script>

The following code creates the label (and adds it to the head) through js ):
Copy codeThe Code is as follows:
Var head = document. getElementsByTagName ('head') [0];
Var script = document. createElement ('script ');
Script. type = 'text/javascript ';
Script. src = 'call. js ';
Head. appendChild (script );

After loading call. js, we need to call the method. However, JavaScript cannot be called immediately after header. appendChild (script. Because the browser loads this js asynchronously, we don't know when it will finish loading. However, we can monitor events to determine whether helper. js is loaded. (Assume that call. js has a callback method)
Copy codeThe Code is as follows:
Var head = document. getElementsByTagName ('head') [0];
Var script = document. createElement ('script ');
Script. type = 'text/javascript ';
Script. onreadystatechange = function (){
If (this. readyState = 'complete ')
Callback ();
}
Script. onload = function (){
Callback ();
}
Script. src = 'helper. js ';
Head. appendChild (script );

I have set two event listening functions, because onreadystatechange is used in ie, while gecko, webkit browser, and opera both support onload. In fact, this. readyState = 'complete' does not work very well. Theoretically, the state change is as follows:
0 uninitialized
1 loading
2 loaded
3 interactive
4 complete
However, some statuses are skipped. In ie7, we can only obtain one of loaded and completed, but not both of them. The reason may be whether reading from the cache affects the status change or other reasons. It is best to change the condition to this. readyState = 'loaded' | this. readyState = 'complete'

The implementation of jQuery is as follows:
Copy codeThe Code is as follows:
Var head = document. getElementsByTagName ('head') [0];
Var script = document. createElement ('script ');
Script. type = 'text/javascript ';
Script. onload = script. onreadystatechange = function (){
If (! This. readyState | this. readyState = "loaded" | this. readyState = "complete "){
Help ();
// Handle memory leak in IE
Script. onload = script. onreadystatechange = null;
}};
Script. src = 'helper. js ';
Head. appendChild (script );

Another simple case is to write the help () call in helper. at the end of js, It can be ensured in helper. after loading JavaScript code, it can automatically call help (). Of course, it is not suitable for your application.

Note:

1. Because the src of the script tag can access resources across domains, this method can simulate ajax to solve the problem of cross-origin ajax access.
2. If the html code returned by ajax contains a script, inserting it directly into the dom using innerHTML cannot make the script in html take effect. The original code of jquery().html (html) in the rough section. jQuery also parses the input parameters, strip the script code, and dynamically creates the script tag, html added to the dom using jQuery's html method can be executed if the script is included. For example:
Copy codeThe Code is as follows:
JQuery ("# content" pai.html ("<script> alert ('A'); <\/script> ");

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.