This article describes the example code about four ways to dynamically introduce js. Share it for your reference, as follows:
<html> <head> <meta content="text/html;charset=utf-8" http-equiv="content-type"> <title> </title> <script src='' ></script> <script src=""></script> </head> <body> </body> </html>
alert("hello! I am "); var str="1";
//The first method: direct but this will overwrite the current page.//("<script src=''><\/script>"); //The second method: dynamically change the src attribute of existing script//="" //The third method: dynamically create script elements/* var oHead = ('HEAD').item(0); var oScript= ("script"); = "text/javascript"; =""; (oScript); */ //In fact, the principle is to use dom to dynamically introduce a js into the file, and you can communicate with the original js~//alert(str); /*The above three methods adopt the asynchronous loading mechanism, that is, during the loading process, the page will go down. If this happens, there will be problems. For example, the above str cannot be accessed because when the program executes alert(str), Ing... is still loading... Then the fourth type is based on ajax request, and it is recommended */ function GetHttpRequest() { if ( ) // Gecko return new XMLHttpRequest() ; else if ( ) // IE return new ActiveXObject("") ; } function ajaxPage(sId, url){ var oXmlHttp = GetHttpRequest() ; = function() { if ( == 4) { includeJS( sId, url, ); } } ('GET', url, false);//Synchronous operation (null); } function includeJS(sId, fileUrl, source) { if ( ( source != null ) && ( !( sId ) ) ){ var oHead = ('HEAD').item(0); var oScript = ( "script" ); = "text/javascript"; = sId; = source; ( oScript ); } } ajaxPage( "scrA", "" ); alert( "The main page dynamically loads JS scripts."); alert( "The main page dynamically loads and takes the variables there:" + str );
All the content expressed above is dynamic introduction of js. I hope that the content of this article has certain reference value for everyone's study or work. If you have any questions, you can leave a message to communicate. Thank you for your support.