Several methods of synchronous asynchronous dynamic introduction of JS file _javascript skills

Source: Internet
Author: User

Dynamically Loading JS files

Sometimes we need to introduce different JS files according to different parameters, and we can't meet our needs by using HTML to write tags directly, summarize several methods, and the various requirements of synchronous asynchronous loading.

I. Direct loading

<div id= "divID" ></div>
<script>

Two. Asynchronous loading, concurrent execution, but the introduction of JS content can not be directly used

1.1 Direct document.write
 document.write ("<script src= ' test.js ' ><\/script>"); 
1.2 Dynamically changing existing script SRC attributes
 //pages have <script src= ' id= ' s1 ' ></script> 
(' document.getElementById ') . src= "Test.js";
 1.3 Dynamically Create JS
 var rootobject=document.getelementbyid ("divID");
 var oscript = document.createelement ("script");
 Oscript.type = "Text/javascript"; 
 OSCRIPT.SRC = Test.js; There is a method in the Test.js method function test () {alert ("Test");}
 Rootobject.appendchild (oscript); 
 2.0 Call JS
 Test ()//No error in IE, there will be errors in Firefox, because Firefox defaults to asynchronous loading (in the request to the server to load the Test.js file, continue down execution, call the test () method, You can't find this method naturally)

Three. Synchronous loading, one-step loading, the introduction of JS content can be directly used

var skip={}; Gets the XMLHttpRequest object, which provides the protocol that the client communicates with the HTTP Server skip.getxmlhttprequest=function () {if window. 
 XMLHttpRequest)//except IE, other browsers return the new XMLHttpRequest (); else if (window. 
ActiveXObject)//IE return new ActiveXObject ("Msxml2.xmlhttp"); },//import content Skip.includejstext =function (rootobject,jstext) {if (rootobject!= null) {var oscript = Document.createel
 Ement ("script"); 
Oscript.type = "Text/javascript"; 
Oscript.id = sId; 
OSCRIPT.SRC = FILEURL; 
Oscript.defer = true; 
Oscript.text = Jstext; 
Rootobject.appendchild (Oscript);
 alert (Oscript.text); },///import file Skip.includejssrc =function (Rootobject, FILEURL) {if (rootobject!= null) {var oscript = Document.cre 
 Ateelement ("script"); 
 Oscript.type = "Text/javascript"; 
 OSCRIPT.SRC = FILEURL; 
 Rootobject.appendchild (Oscript); 
 },///Skip.addjs=function (Rootobject, url) {var oxmlhttp = skip.getxmlhttprequest (); Oxmlhttp.onreadystatechange = function () {//In fact, when the second call to import JS, because in the browser there is this *.JS file, it is not in the access server, it is not in the implementation of this method, this method is only set to asynchronous to use if (oxmlhttp.readystate = = 4) {//When the execution is completed (returned the response) to execute the IF (oxmlhttp.status = = 200 | | 
 Oxmlhttp.status = = 304) {//200 has read the corresponding URL file, 404 indicates that the file does not exist skip.includejssrc (rootobject, URL); 
 else{alert (' XML request error: ' + oxmlhttp.statustext + ' (' + oxmlhttp.status + ') '); //1.true indicates that the script will continue after the Send () method without waiting for the response from the server, and there is a method called to onReadyStateChange () in the Open () method.
By setting this argument to "false", you omit the extra onreadystatechange code, which means that the method behind send () is not executed until the server returns a response. 2. Synchronous execution of the Oxmlhttp.send () method after Oxmlhttp.responsetext has returned the corresponding content, and asynchronous or empty, only in oxmlhttp.readystate = = 4 o'clock only content,
Anyway, the operation after Oxmlhttp.send () is equivalent to Oxmlhttp.readystate = 4 operation, it is equivalent to only this kind of state. Oxmlhttp.open (' Get ', url, false); 
When the URL is JS file, IE will automatically generate ' <script src= ' *.js ' type= ' text/javascript ' > </scr ', FF will not ipt> (null);
Skip.includejstext (Rootobject,oxmlhttp.responsetext);
}
};
var Rootobject=document.getelementbyid ("divID"); Skip.addjs (Rootobject, "test.js")//test.js file contains Funciotn test () {alert ("test");The test ()///will not go wrong even if called immediately. </script>

Summarize:

1. IE dynamically load JS file, it defaults to sync, you can not set the synchronization (also can direct call SKIP.INCLUDEJSSRC ())

2. FF dynamically loaded JS file, it defaults to asynchronous, to set to sync, loaded directly after the call will not be wrong

3. Whether IE or FF in the dynamic loading of JS content, no request server, there will be no asynchronous problems

Note: Whether IE or FF in the page load JS (that is, the entire page), are loaded for synchronization, unless you set the script properties Defer= "True" (this property seems to be only valid for IE)

The above is small series for everyone to bring the synchronous asynchronous dynamic introduction of JS Files of the summary of the full content of several methods, I hope to help you, a lot of support cloud Habitat Community ~

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.