Bạn có thể sử dụng các sự kiện onload
của yếu tố kịch bản đối với hầu hết các trình duyệt, và sử dụng một hàm callback:
Edit: Bạn có thể không thực sự đình chỉ thi hành các mã khi bạn tải tập lệnh theo cách này (và thực hiện các yêu cầu Ajax đồng bộ là một ý tưởng tồi tệ nhất trong các lần).
Nhưng bạn có thể callbacks chuỗi, vì vậy nếu bạn có một số mã mà phụ thuộc vào cả hai, Two.js và Three.js, bạn có thể chuỗi những hành động bốc, ví dụ:
loadScript('http://example.com/Two.js', function() {
// Two.js is already loaded here, get Three.js...
loadScript('http://example.com/Three.js', function() {
// Both, Two.js and Three.js loaded...
// you can place dependent code here...
});
});
Thực hiện:
function loadScript(url, callback) {
var head = document.getElementsByTagName("head")[0],
script = document.createElement("script"),
done = false;
script.src = url;
// Attach event handlers for all browsers
script.onload = script.onreadystatechange = function(){
if (!done && (!this.readyState || // IE stuff...
this.readyState == "loaded" || this.readyState == "complete")) {
done = true;
callback(); // execute callback function
// Prevent memory leaks in IE
script.onload = script.onreadystatechange = null;
head.removeChild(script);
}
};
head.appendChild(script);
}
Đối với IE, sự kiện onreadystatechange
có bị ràng buộc.
Phiên bản câu hỏi này không được hỏi hàng ngàn lần? –