Sự khác nhau cơ bản giữa 3 cách này để tải js lười biếng hoặc tải ondemand là gì và tại sao?tải chậm javascript
kịch bản 1:
$.getScript = function(url, callback, cache){
$.ajax({
type: "GET",
url: url,
success: callback,
dataType: "script",
cache: cache
});
};
script2:
function require(file, callback) {
var script = document.getElementsByTagName('script')[0],
newjs = document.createElement('script');
// IE
newjs.onreadystatechange = function() {
if (newjs.readyState === 'loaded' || newjs.readyState === 'complete') {
callback();
}
};
// others
newjs.onload = function() {
callback();
};
newjs.src = file;
script.parentNode.insertBefore(newjs, script);
}
document.getElementById('id').onclick = function() {
require('ondemand.js', function() {
extraFunction('loaded from the parent page');
document.body.appendChild(document.createTextNode('done!'));
});
};
script3:
$L = function (c, d) {
for (var b = c.length, e = b, f = function() {
if (!(this.readyState
&& this.readyState !== "complete"
&& this.readyState !== "loaded")) {
this.onload = this.onreadystatechange = null;
--e || d()
}
}, g = document.getElementsByTagName("head")[0], i = function (h) {
var a = document.createElement("script");
a.async = true;
a.src = h;
a.onload = a.onreadystatechange = f;
g.appendChild(a)
}; b;) i(c[--b])
};
Nếu bạn đã viết các hàm đó, tôi hy vọng bạn nhận ra rằng 'readyState == 'loaded'' xảy ra * trước * tập lệnh được thực hiện và'' complete'' xảy ra * sau *. – zzzzBov
có đúng ... thậm chí tôi đang lên kế hoạch phân tích cú pháp tập lệnh và không thực thi vì việc thực hiện mất nhiều thời gian hơn phân tích cú pháp – paul