Home >Web Front-end >JS Tutorial >Basic ideas and implementation functions of dynamically inserting scripts in JavaScript_javascript skills

Basic ideas and implementation functions of dynamically inserting scripts in JavaScript_javascript skills

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-05-16 17:16:051257browse

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 and set its src attribute, type attribute, etc.

2 , insert the script node into the page and load the js file

which is equivalent to adding to the page, except This process is completed dynamically, and a function is specially encapsulated for this purpose:

Copy code The code is as follows:

// Dynamically insert script tags
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 tag
** IE6/7/8 supports onreadystatechange event
** IE9/10 supports onreadystatechange and onload events
** Firefox/Chrome/Opera supports onload events
*/

// Determine IE8 and below browsers
var isIE = ! -[1,];
if(isIE){
alert('IE')
oScript.onreadystatechange = function(){
if(this.readyState == 'loaded' || this .readyState == 'complete'){
callback();
}
}
} else {
// IE9 and above browsers, Firefox, Chrome, Opera
oScript .onload = function(){
callback();
}
}
document.body.appendChild(oScript);
}

Used as follows :
Copy code The code is as follows:

createScript('xxx.js', function() {
console.log('OK');
});
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn