Basic Idea and implementation functions of dynamically inserting scripts in JavaScript

Source: Internet
Author: User

In daily front-end development, there is an occasional need to dynamically insert javascript code. The basic idea is:

1. dynamically create a script tag and set its src and type attributes.

2. Insert the script node into the page and load the js file.

That is, it is equivalent to <script type = "text/javascript" src = "xxx. js "> </script> is added to the page, but this process is dynamically completed. Therefore, a function is encapsulated to implement it:
Copy codeThe Code is as follows:
// Dynamically insert a script tag
Function createScript (url, callback ){
Var oScript = document. createElement ('script ');
OScript. type = 'text/javascript ';
OScript. async = true;
OScript. src = url;
/*
** Onload and onreadystatechange events of script labels
** Internet Explorer 6/7/8 supports onreadystatechange events.
** IE9/10 supports onreadystatechange and onload events.
** Firefox/Chrome/Opera supports onload events.
*/

// Judge IE8 and the following browsers
Var isIE =! -[1,];
If (isIE ){
Alert ('ie ')
OScript. onreadystatechange = function (){
If (this. readyState = 'loaded' | this. readyState = 'complete '){
Callback ();
}
}
} Else {
// IE9 and later browsers, Firefox, Chrome, and Opera
OScript. onload = function (){
Callback ();
}
}
Document. body. appendChild (oScript );
}

The usage is as follows:
Copy codeThe Code is as follows:
CreateScript ('xxx. js', function (){
Console. log ('OK ');
});

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.