我有一个使用$(document).ready的脚本,但它不使用jQuery中的任何其他内容。我想通过删除jQuery依赖项来减轻它。
如何在不使用jQuery的情况下实现我自己的$(document).ready功能?我知道,使用window.onload将不同,因为window.onlead在加载所有图像、帧等后启动。
我有一个使用$(document).ready的脚本,但它不使用jQuery中的任何其他内容。我想通过删除jQuery依赖项来减轻它。
如何在不使用jQuery的情况下实现我自己的$(document).ready功能?我知道,使用window.onload将不同,因为window.onlead在加载所有图像、帧等后启动。
当前回答
只需将其添加到HTML页面的底部。。。
<script>
Your_Function();
</script>
因为,HTML文档是按上下顺序解析的。
其他回答
编辑@duskwuff以支持Internet Explorer 8。不同的是,使用匿名函数对regex和setTimeout的函数测试进行了新的调用。
此外,我将超时设置为99。
function ready(f){/in/.test(document.readyState)?setTimeout(function(){ready(f);},99):f();}
大多数普通的JS Ready函数都不考虑在文档加载后设置DOMContentLoaded处理程序的情况——这意味着函数永远不会运行。如果在异步外部脚本(<script async src=“file.js”></script>)中查找DOMContentLoaded,则可能会发生这种情况。
只有当文档的readyState尚未交互或完成时,下面的代码才会检查DOMContentLoaded。
var DOMReady = function(callback) {
document.readyState === "interactive" || document.readyState === "complete" ? callback() : document.addEventListener("DOMContentLoaded", callback());
};
DOMReady(function() {
//DOM ready!
});
如果您也想支持IE:
var DOMReady = function(callback) {
if (document.readyState === "interactive" || document.readyState === "complete") {
callback();
} else if (document.addEventListener) {
document.addEventListener('DOMContentLoaded', callback());
} else if (document.attachEvent) {
document.attachEvent('onreadystatechange', function() {
if (document.readyState != 'loading') {
callback();
}
});
}
};
DOMReady(function() {
// DOM ready!
});
这个解决方案怎么样?
// other onload attached earlier
window.onload=function() {
alert('test');
};
tmpPreviousFunction=window.onload ? window.onload : null;
// our onload function
window.onload=function() {
alert('another message');
// execute previous one
if (tmpPreviousFunction) tmpPreviousFunction();
};
实际上,如果您只关心Internet Explorer 9+,那么这段代码就足以取代jQuery.ready:
document.addEventListener("DOMContentLoaded", callback);
如果您担心Internet Explorer 6和一些非常奇怪和罕见的浏览器,这将奏效:
domReady: function (callback) {
// Mozilla, Opera and WebKit
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", callback, false);
// If Internet Explorer, the event model is used
} else if (document.attachEvent) {
document.attachEvent("onreadystatechange", function() {
if (document.readyState === "complete" ) {
callback();
}
});
// A fallback to window.onload, that will always work
} else {
var oldOnload = window.onload;
window.onload = function () {
oldOnload && oldOnload();
callback();
}
}
},
这很好https://stackoverflow.com/a/11810957/185565穷人的解决方案。一条评论认为,这是在紧急情况下纾困的一种对策。这是我的修改。
function doTheMagic(counter) {
alert("It worked on " + counter);
}
// wait for document ready then call handler function
var checkLoad = function(counter) {
counter++;
if (document.readyState != "complete" && counter<1000) {
var fn = function() { checkLoad(counter); };
setTimeout(fn,10);
} else doTheMagic(counter);
};
checkLoad(0);