我仍然通過製作自己的加載程序來學習;這裏是我的進步:動態加載JavaScript,檢查所有javascript是否加載
<!DOCTYPE html>
<html>
<head>
<title>test</title>
(function($){
$.plugin = {
loadJS: function(src, onload, onerror){
var script = document.createElement("script");
script.type = "text/javascript";
script.src = src;
script.onload = onload;
script.onerror = onerror;
script.onreadystatechange = function() {
var state = this.readyState;
if (state === 'loaded' || state === 'complete') {
script.onreadystatechange = null;
onload();
}
};
document.body.appendChild(script);
},
loader: function(o) {
var loaded = ({js:[],css:[]});
// http://www.crockford.com/javascript/private.html
var that = this;
var phase = 0;
$.each(o["js"], function(key,src) {
that.loadJS(src,
function(){
loaded['js'].push(src);
});
});
console.log(loaded['js'].length)
// IF JS ALL LOADED, this is the main problem
if (loaded['js'].length == o["js"].length) {
alert('problem solved')
that.loadJS(o["script"]);
};
}
};
})(jQuery);
</script>
</head>
<body>
<script>
$(document).ready(function() {
$.plugin.loader({
js: [
'1.js', // async
'2.js', // async
'3.js', // async
'4.js' // async
],
script: '5.js', // after js loaded
debug: 1
});
});
</script>
</body>
</html>
問題是我仍然沒有得到如何在JS工作。上述同樣的它會隨機加載JS我作爲它的異步*承擔一切alert('this is x.js loaded')
內1-5.js
像
// check goes randomly here
1.js or 1 js loaded
3.js 2 js loaded
2.js 3 js loaded
4.js 4 js loaded
// it should be here
所以邏輯是,當我所有的JS是負載if (loaded['js'].length == o["js"].length) {alert('problem solved')};
應該工作。但它並不以某種方式附加到事件上。
如何檢查我的所有js是否已加載?
這僅僅是一個學習JS的項目,或者你打算將它用於生產代碼?您可能想要查看現有的腳本加載器。 –
學習,但我會稍後在學習其他腳本加載器以符合我們的需要後,將其用於生產,但我意識到很多事情沒有像檢查相同的域等執行的東西,但我肯定不好,屆時會好起來。 :) –