1, Direct document.write
The code is as follows |
Copy Code |
<script language= "JavaScript" > document.write ("<script src= ' test.js ' ></script>"); </script> |
2, dynamically changing the SRC attribute of the existing script
The code is as follows |
Copy Code |
<script src= ' id= "S1" ></script> <script language= "JavaScript" > S1.src= "Test.js" </script> |
3. Dynamically creating script elements
The code is as follows |
Copy Code |
<script> var ohead = document.getElementsByTagName (' head '). Item (0); var oscript= document.createelement ("script"); Oscript.type = "Text/javascript"; Oscript.src= "Test.js"; Ohead.appendchild (Oscript); </script> |
Above three kinds of methods can be suitable for my request, but personally feel not applicable, so look for jquery/45691.htm ">jquery dynamic load JS file, this does not have a very good code
The code is as follows |
Copy Code |
<script type= "Text/javascript" src= ". /jquery.js "></script> <script type= "Text/javascript" > $ (function () { $ (' #loadButton '). Click (function () { $.getscript (' New.js ', function () { Newfun (' Checking new script ');//This function is inside the new.js, run this function when clicked click }); }); }); </script> <body> <button type= "button" id= "Loadbutton" >Load</button> |
The above code can fully meet my requirements, and the following attached a code to load JS and CSS code
Dynamic load js, css file code:
code is as follows |
copy code |
Dynamic load File code $.extend ({ Includepath: ", Include:function (file) { var files = typeof File = = "string"? [File]: file; for (var i = 0; i < files.length; i++) { var name = Files[i].replace (/^s|s$/g, ""); var att = name.split ('. '); var ext = att[att.length-1].tolowercase (); var iscss = ext = "CSS"; var tag = iscss? "Link": "Script"; var attr = iscss? "Type= ' text/css ' rel= ' stylesheet '": "language= ' JavaScript ' type= ' Text/javascript '"; var link = (iscss? "href": "src") + "= '" + $.includepath + name + "'"; if ($ (tag + "[" + link + "]"). Length = = 0) document.write (""); } } }); How to use $.includepath = ' scripts/workspace/'; $.include ([' getvehiclegroup.js ']);
|
Note: The code department is reproduced. But it's been used.
2. Immediate use of the method in the JS file
Because it is dynamically loaded. Consider the reasons for the network. Use the methods in the JS file immediately to make an error. But you can use the bottom code
The code is as follows |
Copy Code |
function _getvehiclegroup () { if ("undefined" = = typeof (Getvehiclegroupisok)) { SetTimeout ("_getvehiclegroup ()", 200); Return } The method of dynamically loading JS file Getvehiclegroup (); } |
Note: To add a tag to the JS file to be loaded, such as:
code is as follows |
copy code |
var Getvehiclegroupisok = "Enable"; |