JavaScript dynamically loads JS files (supports various browsers)

Source: Internet
Author: User
Tags script tag

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>

All three of these methods are executed asynchronously, that is, the script on the main page continues to run while the scripts are loaded, and if you use the above method, the following code will not get the desired result.
To dynamically load the JS script: A.js, the following is the contents of the file.

The code is as follows Copy Code
var str = "China";
Alert ("This is the variable in a.js:" + str);

See below for reference example

The code is as follows Copy Code

function Loadjs (sid,jsurl,callback) {
var nodehead = document.getElementsByTagName (' head ') [0];
var nodescript = null;
There is no load
if (document.getElementById (SID) = = null) {
Nodescript = document.createelement (' script ');
Nodescript.setattribute (' type ', ' text/javascript ');
Nodescript.setattribute (' src ', jsurl);
Nodescript.setattribute (' id ', sid);
if (callback!= null) {
Nodescript.onload = Nodescript.onreadystatechange = function () {
if (Nodescript.ready) {
return false;
}
if (!nodescript.readystate | | nodescript.readystate = "Loaded" | | nodescript.readystate = = ' complete ') {
Nodescript.ready = true;
Callback ();
}
};
}
Nodehead.appendchild (Nodescript);
} else {
if (callback!= null) {
Callback ();
}
}
}

Because the user clicks, loading JS, but if JS already exists then do not have to load, call the callback function directly. So I don't have to remove the script tag here. A simple test does not seem to cause a memory leak.

Take advantage of the current popular jquery


jquery Append this method and then changed the code to

The code is as follows Copy Code
$ (document). Append ("<script type= ' text/javascript ' src= '" +_webinfpath+ "/js/util.js ' </script>");

Ok

Let me give you a detailed introduction.


First part of the HTML file code:

The code is as follows Copy Code

<script type= "Text/javascript" src= "/js/jquery-1.4.2.js" ></script>
<script type= "Text/javascript" src= "/js/common.js" ></script>

<select id= "Ts1" jselect= "Ts1" ></select><!--dropdown box using-->

And then the common.js part of the code:

The code is as follows Copy Code
var _webinfpath = ""; Project Context Web-inf Path


Initial page

The code is as follows Copy Code
$ (document). Ready (function () {
_webinfpath = Getwebrootpath (); Get Project Context Path
$ (document). Append ("<script type= ' text/javascript ' src= '" +_webinfpath+ "/js/util.js ' </script>");
Jselect (); Drop down box fill value
}
);

Get Project and Path

The code is as follows Copy Code
function Getwebrootpath () {
var path = Location.href;
var Patharr = Path.split ("/");
return patharr[0]+ "//" +patharr[2]+ "/" +patharr[3];
}

Drop down box fill value

The code is as follows Copy Code
function Jselect () {
$.each ($ ("select"), function () {
var jqueryobj = $ (this);
var Jselect = $ (this). attr ("Jselect");
$.ajax ({
URL: _webinfpath+ "/servlet/ajaxservlet.do",//(here Ajaxservlet is actually a common servlet I wrote, the effect is the same as struts, after configuration, will automatically execute the method inside the action)
data:{"method": "Getjselect", "act": "Glob", "Jselect": Jselect},
Type: "Post",
Async: "True",
DataType: "JSON",
Success:function (Result) {
Fillselect (result,jqueryobj.attr ("id"));
}
});
});
}

Then there is part of the code for the Util.js file:

  code is as follows copy code

-------------------------------------drop-down Box Begin---------------------
/**
* Fill Drop-down box for call
* Jsonarr: josn array for storing JSELECTVO objects
* Selectid:selectid
*/
function Fillselect (Jsonarr,selectid) {
if (Jsonarr==null | | jsonarr.length==0) {
return false;
}
var content = "";
$.each (Jsonarr,function () {
Content + + jselect_addoption (this);
});
$ ("#" +selectid). Append (content);
}

Assembly option
function Jselect_addoption (_option) {
var arr = new Array ();
Arr.push ("<option value= '" + _option.value+ "' >");
Arr.push (_option.name);
Arr.push ("</option>");
Return Arr.join ("");
}

-------------------------------------dropdown box End---------------------


Ajax using asynchronous Load methods

Principle: Use XMLHTTP to get the content of the script, and then create a script object.
Note: A.js must be saved with UTF8 encoding, without error. Because the server and XML use UTF8 encoding to transmit data. There is also a way to set the default encoding on the Web server, and if JS is saved as GB2312, the default file encoding for the server is GB2312, so that there is no error.
Main Page code:

The code is as follows Copy Code
<script language= "JavaScript" >
function Gethttprequest ()
{
if (window. XMLHttpRequest)//Gecko
return new XMLHttpRequest ();
else if (window. ActiveXObject)//IE
return new ActiveXObject ("Msxml2.xmlhttp");
}
function ajaxpage (sId, url) {
var oxmlhttp = Gethttprequest ();
Oxmlhttp.onreadystatechange = function ()
{
if (oxmlhttp.readystate = 4)
{
if (oxmlhttp.status = = | | oxmlhttp.status = 304)
{
Includejs (sId, URL, oxmlhttp.responsetext);
}
Else
{
Alert (' XML request error: ' + oxmlhttp.statustext + ' (' + oxmlhttp.status + ') ');
}
}
}
Oxmlhttp.open (' Get ', url, true);
Oxmlhttp.send (NULL);
}
function Includejs (sId, FILEURL, source)
{
if (source!= null) && (!document.getelementbyidx_x (sId)) {
var ohead = Document.getelementsbytagname_r (' head '). Item (0);
var oscript = document.createelement_x ("script");
Oscript.language = "JavaScript";
Oscript.type = "Text/javascript";
Oscript.id = sId;
Oscript.defer = true;
Oscript.text = source;
Ohead.appendchild (Oscript);
}
}
Ajaxpage ("SCRA", "b.js");
Alert ("Home page dynamically loads the JS script.") ");
Alert ("Main page dynamically loads A.js and takes the variables:" + str);
</script>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.