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 file
<html xmlns="http:///1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <title>Load on demandJavaScriptExample of code</title> <script type="text/javascript"> function JsLoader(){ =function(url){ //Get all <script> tags var ss=("script"); //Determine whether the specified file has been included. If it has been included, the onsuccess event will be triggered and returned for (i=0;i<;i++){ if (ss[i].src && ss[i].(url)!=-1){ (); return; } } //Create script node and set its properties to an outreach JavaScript file s=("script"); ="text/javascript"; =url; //Get the head node and insert <script> into it var head=("head")[0]; (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 or not //==function(){ ==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 ( && =="loading") return; (); } =function(){ (s); (); } }; //Define the event of loading successfully =function(){}; //Define the failed event =function(){}; } function btnClick(){ //Create an object var jsLoader=new JsLoader(); //Definition loading process successfully =function(){ sayHello(); } //Definition loading failure handler =function(){ alert("File loading failed!"); } //Start loading (""); } </script> </head> <body> <label> <input type="submit" name="Submit" onClick="javascript:btnClick()" value="Load JavaScript File"> </label> </body> </html>
(2) Create a new file, including the following code:
// JavaScript Document function sayHello(){ alert("Hello World! JavaScript file is loaded successfully"); } // JavaScript Document function sayHello(){ alert("Hello World! JavaScript file is loaded successfully"); }