Skip to content

Commit

Permalink
Create 异步加载JS文件并执行回调函数.js
Browse files Browse the repository at this point in the history
  • Loading branch information
Rain120 authored Apr 3, 2018
1 parent 9eefb28 commit 7f7abe5
Showing 1 changed file with 21 additions and 0 deletions.
21 changes: 21 additions & 0 deletions 异步加载JS文件并执行回调函数.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// 异步加载JS文件并执行回调函数

function loadJS(url, callback) {
var script = document.createElement('script');
var head = getElementsByTagName('head')[0];
var loaded;
script.src = url;
if (typeof callback === 'function') {
script.onload = script.onreadystatechange = function () {
if (!loaded && (!script.readyState || /loaded|complete/.test(script.readyState))) {
script.onload = script.onreadystatechange = null;
loaded = true
callback();
}
}
}
head.appendChild(script);
}
loadJS('test.js', function() {
console.log('callback');
});

0 comments on commit 7f7abe5

Please sign in to comment.