延迟回调,直到脚本添加到文档? [英] Delay callback until script is added to document?
本文介绍了延迟回调,直到脚本添加到文档?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果脚本实际附加到文档之前,如何才能使回调无法运行?
How can I get the callback to not run until the script is actually appended to the document?
function addScript(filepath, callback){
if (filepath) {
var fileref = document.createElement('script');
fileref.setAttribute("type","text/javascript");
fileref.setAttribute("src", filepath);
if (typeof fileref!="undefined")
document.getElementsByTagName("head")[0].appendChild(fileref);
}
if (callback) {
callback();
}
}
推荐答案
In理想的世界,你可以使用< script />
标签的 onload
属性;
In the ideal world, you could use the onload
property of the <script />
tag;
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);
}
}
然而,这在IE中不起作用,因此需要mega-h4x;
However, this doesn't work in IE, so mega-h4x are required;
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)
是多余的,因为它总是评估为true,所以你可以做 head.appendChild(fileref);
直接,如我的例子。
FWIW, your if (typeof fileref != "undefined")
was redundant, as it will always evaluate to true, so you can just do head.appendChild(fileref);
directly, as in my example.
这篇关于延迟回调,直到脚本添加到文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文