Generally speaking, if all required JavaScript code is loaded at once, the initial web page will slow down, but many loaded codes do not need to be used, and this unnecessary performance waste should be avoided. If you want to dynamically load JavaScript code, you can use the DOM model to add a <script> node in the HTML document and set the src attribute of this node (i.e., an outreach Javascript file) to JavaScript code that needs to be dynamically loaded.
Here is an example of completing such a function:
(1) Create a new JsLoaderTest.html file
<html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <title>Example of loading JavaScript code on demand</title> <script type="text/javascript"> function JsLoader(){ this.load=function(url){ //Get all <script> tags var ss=document.getElementsByTagName("script"); //Test whether the specified file has been included. If it has been included, trigger the onsuccess event and return for (i=0;i<ss.length;i++){ if (ss[i].src && ss[i].src.indexOf(url)!=-1){ this.onsuccess(); return; } } //Create script node and set its attributes to the outreach JavaScript file s=document.createElement("script"); s.type="text/javascript"; s.src=url; //Get head node and insert <script> into var head=document.getElementsByTagName("head")[0]; head.appendChild(s); //Get your own reference var self=this; //For IE browser, use the readystatechange event to determine whether the load is successful//For other browsers, use the onload event to determine whether the load is successful//s.onload=s.onreadystatechange=function(){ s.onload=s.onreadystatechange=function(){ //In this function, this pointer refers to the s node object, not the JsLoader instance, //So you must use self to call the onsuccess event, the same below. if (this.readyState && this.readyState=="loading") return; self.onsuccess(); } s.onerror=function(){ head.removeChild(s); self.onfailure(); } }; //Define the loading success event this.onsuccess=function(){}; //Define the failed event this.onfailure=function(){}; } function btnClick(){ //Create the object var jsLoader=new JsLoader(); //Define the loading success handler jsLoader.onsuccess=function(){ sayHello(); } //Define loading failure handler jsLoader.onfailure=function(){ alert("File loading failed!"); } //Start loading jsLoader.load("hello.js"); } </script> </head> <body> <label> <input type="submit" name="Submit" onClick="javascript:btnClick()" value="Loading JavaScript file"> </label> </body> </html>(2) Create a new hello.js file, including the following code:
// JavaScript Document function saysHello(){ alert("Hello World! Successfully loaded JavaScript file"); } // JavaScript Documentfunction saysHello(){ alert("Hello World! Successfully loaded JavaScript file"); }