Trong thế giới lý tưởng, bạn có thể sử dụng tài sản của onload
thẻ <script />
;
function addScript(filepath, callback){
if (filepath) {
var fileref = document.createElement('script');
fileref.onload = callback;
fileref.setAttribute("type","text/javascript");
fileref.setAttribute("src", filepath);
if (typeof fileref!="undefined")
document.getElementsByTagName("head")[0].appendChild(fileref);
}
}
Tuy nhiên, this doesn't work in IE, vì vậy cần phải có mega-h4x;
function addScript(filepath, callback) {
if (filepath) {
var fileref = document.createElement('script');
var done = false;
var head = document.getElementsByTagName("head")[0];
fileref.onload = fileref.onreadystatechange = function() {
if (!done && (!this.readyState || this.readyState === "loaded" || this.readyState === "complete")) {
done = true;
callback();
// Handle memory leak in IE
fileref.onload = fileref.onreadystatechange = null;
if (head && fileref.parentNode) {
head.removeChild(fileref);
}
}
};
fileref.setAttribute("type", "text/javascript");
fileref.setAttribute("src", filepath);
head.appendChild(fileref);
}
}
FWIW, if (typeof fileref != "undefined")
của bạn là không cần thiết, vì nó sẽ luôn luôn đánh giá đúng, vì vậy bạn chỉ có thể làm head.appendChild(fileref);
trực tiếp, như trong ví dụ của tôi.
tôi không thể chạm vào kịch bản tự động bao gồm. – dezman