JavaScript dynamic insertion script basic ideas and functions
- 2020-03-26 23:59:57
- OfStack
In daily front-end development, occasionally there is a need to dynamically insert javascript code, the basic idea is:
1. Dynamically create a script tag, set its SRC attribute, type attribute, etc
2. Insert the script node into the page and load the js file
Is equivalent to will < The script type = "text/javascript" SRC = "XXX. Js >" < / script> Added to the page, but the process is done dynamically, this is deliberately encapsulated a function to achieve:
Usage:
1. Dynamically create a script tag, set its SRC attribute, type attribute, etc
2. Insert the script node into the page and load the js file
Is equivalent to will < The script type = "text/javascript" SRC = "XXX. Js >" < / script> Added to the page, but the process is done dynamically, this is deliberately encapsulated a function to achieve:
//Insert script tags dynamically
function createScript(url, callback){
var oScript = document.createElement('script');
oScript.type = 'text/javascript';
oScript.async = true;
oScript.src = url;
/*
** script Of the label onload and onreadystatechange The event
** IE6/7/8 support onreadystatechange The event
** IE9/10 support onreadystatechange and onload The event
** Firefox/Chrome/Opera support onload The event
*/
//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 above, Firefox, Chrome, Opera
oScript.onload = function(){
callback();
}
}
document.body.appendChild(oScript);
}
Usage:
createScript('xxx.js', function(){
console.log('OK');
});