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 ');
});