Four Methods for dynamically loading JS scripts

Source: Internet
Author: User

There are four methods to dynamically load JS scripts:

1. Directly document. Write

<Script language ="JavaScript">

Document. Write ("<SCRIPT src = 'test. js'> <\/SCRIPT>");

</SCRIPT>

 

2. dynamically change the src attribute of an existing script

<SCRIPT src =''Id ="S1"> </SCRIPT>

<Script language ="JavaScript">

S1.src ="Test. js"

</SCRIPT>

 

3. dynamically create script elements

<SCRIPT>

VaROhead = Document. getelementsbytagname ('Head'). Item (0 );

VaROscript = 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 followingCodeThe expected results will not be achieved.

The JS script to be dynamically loaded: A. js. The content of this file is as follows.

VaR STR ="China";

Alert ("This is the variable in A. JS :"+ Str );

 

Homepage code:

<Script language ="JavaScript">

FunctionLoadjs (ID, fileurl)

{

VaRScripttag = Document. getelementbyid (ID );

VaROhead = Document. getelementsbytagname ('Head'). Item (0 );

VaROscript = 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 ("The main page dynamically loads a. js and obtains the variables :"+ 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:

<Script language = "JavaScript" >

FunctionGethttprequest ()

{

If(Window. XMLHttpRequest)// Gecko

Return NewXMLHttpRequest ();

Else If(Window. activexobject)// IE

Return NewActivexobject ("Msxml2.xmlhttp");

}

FunctionAjaxpage (SID, URL ){

VaROxmlhttp = 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);

}

FunctionIncludejs (SID, fileurl, source)

{

If(Source! =Null)&&(! Document. getelementbyid (SID ))){

VaROhead = Document. getelementsbytagname ('Head'). Item (0 );

VaROscript = 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 ("JS scripts are dynamically loaded on the home page. ");

Alert ("The main page dynamically loads a. js and obtains the variables :"+ Str );

</SCRIPT>

Now a JS script is loaded dynamically.

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 ();

Original article: http://hi.baidu.com/ajax/blog/item/bd1b9d163c1fca51f3de3282.html

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.