使用jQuery,我们都知道很棒的.ready()函数:
$('document').ready(function(){});
然而,假设我想运行一个用标准JavaScript编写的函数,而没有库支持它,并且我想在页面准备好处理它后立即启动一个函数。正确的方法是什么?
我知道我能做到:
window.onload="myFunction()";
或者我可以使用body标签:
<body onload="myFunction()">
或者,我甚至可以在页面底部尝试所有内容,但结尾正文或html标记如下:
<script type="text/javascript">
myFunction();
</script>
什么是以jQuery的$.ready()这样的方式发出一个或多个函数的跨浏览器(旧/新)兼容方法?
如果您在不使用jQuery的情况下使用VANILLA纯JavaScript,则必须使用(Internet Explorer 9或更高版本):
document.addEventListener("DOMContentLoaded", function(event) {
// Your code to run since DOM is loaded and ready
});
上面是jQuery.ready的等价物:
$(document).ready(function() {
console.log("Ready!");
});
也可以这样编写SHORTHAND,jQuery将在就绪后运行。
$(function() {
console.log("ready!");
});
不要与以下内容混淆(这并不意味着DOM准备就绪):
不要使用这种自动执行的IIFE:
Example:
(function() {
// Your page initialization code here - WRONG
// The DOM will be available here - WRONG
})();
此IIFE不会等待DOM加载。(我甚至在谈论最新版本的Chrome浏览器!)
准备好的
function ready(fn){var d=document;(d.readyState=='loading')?d.addEventListener('DOMContentLoaded',fn):fn();}
像这样使用
ready(function(){
//some code
});
用于自调用代码
(function(fn){var d=document;(d.readyState=='loading')?d.addEventListener('DOMContentLoaded',fn):fn();})(function(){
//Some Code here
//DOM is avaliable
//var h1s = document.querySelector("h1");
});
支持:IE9+
HubSpot的好人有一个资源,你可以在那里找到纯Javascript方法来实现jQuery的很多优点,包括准备好
http://youmightnotneedjquery.com/#ready
function ready(fn) {
if (document.readyState != 'loading'){
fn();
} else if (document.addEventListener) {
document.addEventListener('DOMContentLoaded', fn);
} else {
document.attachEvent('onreadystatechange', function() {
if (document.readyState != 'loading')
fn();
});
}
}
内联用法示例:
ready(function() { alert('hello'); });