Examples of js methods for dynamically loading scripts, js instances
This article describes how to dynamically load scripts in JavaScript. We will share this with you for your reference. The details are as follows:
Recently, the company's front-end map products need to be divided into modules, which of the following functions can be used by users to attach modules to improve user experience.
So it's really sad to look up data everywhere to study loading js dynamic scripts !, Almost all of them are the same article on the Internet. There are four methods. People who hate copying others' achievements do not add a link to the original article. Ah! The key is that the last method has some errors. After two days of research, I will share with you the materials.
First, we need a loaded js file. I created a package. js file in a fixed folder and wrote the functionOne method in it. The Code is as follows:
Function functionOne () {alert ("loaded successfully ");}
All html files are created in the same directory.
Method 1: directly document. write
Create a function1.html file under the same folder. The Code is as follows:
<Html>
By document. the write method can write scripts to the page, as shown in the Code. Click the "initialize loading" button to load the package. js file, but the method functionOne in the "run now" will not find this method, report an error, and click the second button (via document. write dynamically created "test running effect") can be executed, and the script has been loaded. This method is asynchronous loading (while continuing to execute the subsequent code, opening a thread to execute the script to be loaded), and document. write will overwrite the interface, which is obviously not practical.
Method 2: dynamically change the src attribute of an existing script
Create a function2.html file under the same folder. The Code is as follows:
<Html>
The advantage of this method is that it does not change the interface elements and does not rewrite the interface elements, but it is also asynchronous loading, which has the same problem.
Method 3: dynamically create script elements (asynchronous)
Create a function3.html file under the same folder. The Code is as follows:
<Html>
Compared with the second method, this method does not need to write a script tag on the interface at the beginning. The disadvantage is asynchronous loading, which has the same problem.
These three methods are executed asynchronously. Therefore, when these scripts are loaded, the scripts on the home page continue to run. If the above method is used, the following code will not achieve the expected results.
However, you can add an alert in front of functionOne to block the script running on the home page. Then you find functionOne can be run, or your later code needs to be executed under another button, step by step, or define a timer and execute the subsequent code after a fixed time. However, these methods cannot be used in the project.
In fact, the third method changes to synchronous loading.
Method 4: dynamically create script elements (synchronize)
Create a function4.html file under the same folder. The Code is as follows:
<Html>
This method does not load external js files, but adds subitems to myScript. In Firefox, Safari, Chrome, Opera, and IE9, the code runs normally. However, errors may occur in IE8 or earlier versions. IE regards <script> as a special element and does not allow DOM to access its subnodes. However, you can use the text attribute of the <script> element to develop js Code. The following example is used:
Var myScript = document. createElement ("script"); myScript. type = "text/javascript"; myScript. text = "function functionOne () {alert (\" run successfully \ ") ;}"; document. body. appendChild (myScript); // you can run functionOne () here ();
The modified code can be run in IE, Firefox, Opera, Safari3 and later versions. Although earlier versions of Safari3.0 do not support the text attribute correctly, the text node technology can be used to specify code. To be compatible with earlier versions of Safari, use the following code:
Var myScript = document. createElement ("script"); myScript. type = "text/javascript"; var code = "function functionOne () {alert (\" successfully run \ ") ;}"; try {myScript. appendChild (document. createTextNode (code);} catch (ex) {myScript. text = code;} document. body. appendChild (myScript); // you can run functionOne () here ();
Here, first try the standard DOM text node method, because all browsers support this method except IE8 and below. If this line of code throws an error, it indicates IE8 and below, so you must use the text attribute. The entire process can be represented by the following functions:
function loadScriptString(code){ var myScript= document.createElement("script"); myScript.type = "text/javascript"; try{ myScript.appendChild(document.createTextNode(code)); } catch (ex){ myScript.text = code; } document.body.appendChild(myScript);}
Then you can use this method elsewhere to load the required code. In fact, the code execution in this way is the same as passing the same string to eval () in the global action. But here we can only use code in the string format, but also have limitations. Users generally want to provide methods like loadScriptAddress ("package. js"), so we need to continue to discuss.
Method 5: XMLHttpRequest/ActiveXObject asynchronous loading
Create a function5.html file under the same folder. The Code is as follows:
<Html>
ActiveXObject is available only in IE. Most other browsers support XMLHttpRequest. Through this method, we can dynamically load scripts. It is just asynchronous loading, and functionOne cannot be run. The second operation can be run, but unfortunately, it can be run in IE, Firefox, and Safari. errors may occur in Opera and Chrome, and errors in Chrome are as follows:
However, after the release, there will be no errors in Chrome and Opera.
In fact, if you set "open" to "false", it means synchronous loading. You do not need to set the onreadystatechange event for Synchronous loading.
Method 6: XMLHttpRequest/ActiveXObject synchronous Loading
Here I write a method that is encapsulated as loadJS. js to facilitate future calls. The Code is as follows:
/*** Synchronously load the js script * @ param id the relative or absolute path of the <script> tag id * @ param url js file * @ return {Boolean} returned whether the load is successful, true indicates success. false indicates failure */function loadJS (id, url) {var xmlHttp = null; if (window. activeXObject) // IE {try {// IE6 and later versions can use xmlHttp = new ActiveXObject ("Msxml2.XMLHTTP");} catch (e) {// IE5.5 and later versions can use xmlHttp = new ActiveXObject ("Microsoft. XMLHTTP ") ;}} else if (window. XMLHttpRequest) // Firefox, Opera 8.0 +, Safari, Chrome {xmlHttp = new XMLHttpRequest ();} // synchronously load xmlHttp. open ("GET", url, false); // send a synchronous request. If the browser is Chrome or Opera, it must be published before running. Otherwise, xmlHttp is reported incorrectly. send (null); // 4 indicates that if (xmlHttp. readyState = 4) {// 0 indicates the local access, 200 to 300 indicates that the server is successfully accessed, and 304 indicates that the access is cached if (xmlHttp. status> = 200 & xmlHttp. status <300) | xmlHttp. status = 0 | xmlHttp. status = 304) {var myHead = document. getElementsByTagName ("HEAD "). item (0); var myScript = document. createElement ("script"); myScript. language = "javascript"; myScript. type = "text/javascript"; myScript. id = id; try {// IE8 and the following methods are not supported. You need to set myScript using the text attribute. appendChild (document. createTextNode (xmlHttp. responseText);} catch (ex) {myScript. text = xmlHttp. responseText;} myHead. appendChild (myScript); return true;} else {return false ;}}
The compatibility of the browser and the release and comments of a js file must be clear when Chrome and Opera are used. You only need one sentence to load a js file, for example, loadJS ("myJS", "package. js "). Convenient and practical.
If you want to implement non-publishing, you still have to be compatible with all browsers. At least I have not found such a synchronous loading method. We can only achieve this by asynchronously loading the callback function.
Method 7: Callback Function Method
Create a function7.html file under the same folder. The Code is as follows:
<Html>
All browsers support this method, but the subsequent code must be placed in the callback function, that is, asynchronously loaded. Depends on the need to use! I prefer the sixth method. There are several other methods for asynchronous loading, but my starting point is to Achieve Synchronous loading, so I will not summarize asynchronous loading here.
I hope this article will help you design JavaScript programs.