我有一个使用$(document).ready的脚本,但它不使用jQuery中的任何其他内容。我想通过删除jQuery依赖项来减轻它。

如何在不使用jQuery的情况下实现我自己的$(document).ready功能?我知道,使用window.onload将不同,因为window.onlead在加载所有图像、帧等后启动。


当前回答

我们发现了一个快速而肮脏的跨浏览器实现,它可以用最少的实现实现大多数简单情况:

window.onReady = function onReady(fn){
    document.body ? fn() : setTimeout(function(){ onReady(fn);},50);
};

其他回答

我使用这个:

document.addEventListener("DOMContentLoaded", function(event) { 
    //Do work
});

注意:这可能只适用于较新的浏览器,尤其是以下浏览器:http://caniuse.com/#feat=domcontentloaded

2022版本

2022年,您需要做的就是将defer属性放在脚本上,并将其加载到头部!

参考:https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#attr-推迟

<!doctype html>
<html>
<head>
  <script src="/script.js" defer></script>
</head>
<body>

 <p>In 2022, all you need to do is put the defer attribute on your script, and load it in the head!</p>

</body>
</html>

实际上,如果您只关心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();
        }
    }
},

使用纯JavaScript的最简单方法。没有jQuery:

document.addEventListener("DOMContentLoaded", function(event) {
   // Your code to run since DOM is loaded and ready
});

最小且100%工作

我已经从PlainJS中选择了答案,它对我来说很好。它扩展了DOMContentLoaded,因此它可以在所有浏览器中被接受。


此函数等效于jQuery的$(document).ready()方法:

document.addEventListener('DOMContentLoaded', function(){
    // do something
});

然而,与jQuery不同的是,这段代码只能在现代浏览器中正常运行(IE>8),如果在插入此脚本时(例如通过Ajax)已经呈现了文档,则无法正常运行。因此,我们需要稍微扩展一下:

function run() {
    // do something
}

// in case the document is already rendered
if (document.readyState!='loading') run();
// modern browsers
else if (document.addEventListener) 
document.addEventListener('DOMContentLoaded', run);
// IE <= 8
else document.attachEvent('onreadystatechange', function(){
    if (document.readyState=='complete') run();
});

这基本上涵盖了所有的可能性,是jQuery助手的可行替代品。