Four Methods for loading scripts dynamically in JS

Source: Internet
Author: User

If the JS files are relatively small and a JS file is better, this can reduce the number of connections. The following are four commonly used methods. You can select one based on your needs.
1. Directly document. Write
CopyCode The Code is as follows: <script language = "JavaScript">
Document. Write ("<SCRIPT src = 'test. js'> <\/SCRIPT> ");
</SCRIPT>

2. dynamically change the src attribute of an existing script Copy codeThe Code is as follows: <SCRIPT src = ''id =" S1 "> </SCRIPT>
<Script language = "JavaScript">
S1.src = "test. js"
</SCRIPT>

3. dynamically create script elements Copy codeThe Code is as follows: <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>

These three methods are executed asynchronously. That is to say, when these scripts are loaded, the scripts on the home page continue to run. If the above method is used, the following code will not achieve the expected results.
JS script to be dynamically loaded: A. js. The content of this file is as follows:Copy codeCode: var STR = "China ";
Alert ("this is the variable in A. JS:" + Str );

Homepage code:Copy codeThe Code is as follows: <script language = "JavaScript">
Function loadjs (ID, fileurl)
{
VaR scripttag = Document. getelementbyid (ID );
VaR ohead = Document. getelementsbytagname ('head'). Item (0 );
VaR oscript = Document. createelement ("script ");
If (scripttag) ohead. removechild (scripttag );
Oscript. ID = ID;
Oscript. type = "text/JavaScript ";
Oscript. src = fileurl;
Ohead. appendchild (oscript );
}
Loadjs ("A. js ");
Alert ("loading a. js dynamically on the homepage and taking the variable:" + Str );
</SCRIPT>

After the above code is executed, alert of A. JS is executed and a message is displayed,
However, an error occurs on the home page. No dialog box is displayed. The reason is that 'str' is not defined. Why? This is because when STR is retrieved on the homepage, A. JS is not fully loaded. When you need to execute the script synchronously, you can use the fourth method below.
4. Principle: Use XMLHTTP to get the content of the script and create a script object.
Note: A. js must be UTF-8 encoded and saved without errors. Because the server and XML use utf8 encoding to transmit data.
Homepage code:Copy code The Code is as follows: <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 = 200 | 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 compute dejs (SID, fileurl, source)
{
If (source! = NULL )&&(! Document. getelementbyid (SID ))){
VaR ohead = Document. getelementsbytagname ('head'). Item (0 );
VaR oscript = Document. createelement ("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 ("the main page dynamically loads JS scripts. ");
Alert ("loading a. js dynamically on the homepage and taking the variable:" + Str );
</SCRIPT>

Now a JS script is loaded dynamically.Copy codeThe Code is as follows: var rash = true;
VaR MSG = "";
Function norash ()
{
If (confirm ("are you sure you want to cancel "))
Rash = false;
}
Function rashit ()
{
Setinterval ('getrss () ', inttime );
}
Function getrss ()
{
If (rash = true)
{
Head = Document. getelementsbytagname ('head'). Item (0 );
Script = Document. createelement ('script ');
Script. src = 'include/AutoUpdate. asp ';
Script. type = 'text/JavaScript ';
Script. Defer = true;
Void (head. appendchild (SCRIPT ));
Window. Status = MSG;
}
}
Rashit ();

Note that the text is bold and you can choose the appropriate one.

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.