纯JavaScript等效于jQuery的$ .ready()-页面/ DOM准备就绪时如何调用函数[重复]

本文翻译自:Pure JavaScript equivalent of jQuery's $.ready() - how to call a function when the page/DOM is ready for it [duplicate]

This question already has an answer here: 这个问题已经在这里有了答案:

Okay, this might just be a silly question, though I'm sure there are plenty of other people asking the same question from time to time. 好的,这可能只是一个愚蠢的问题,尽管我敢肯定会有很多其他人不时问同样的问题。 Me, I just want to make 100% sure about it either way. 我,我只是想以任何一种方式100%确定它。 With jQuery we all know the wonderful 有了jQuery,我们都知道精彩之处

$('document').ready(function(){});

However, let's say I want to run a function that is written in standard JavaScript with no library backing it, and that I want to launch a function as soon as the page is ready to handle it. 但是,假设我要运行一个用标准JavaScript编写且没有库支持的函数,并且我想在页面准备好处理后立即启动一个函数。 What's the proper way to approach this? 解决这个问题的正确方法是什么?

I know I can do: 我知道我可以做:

window.onload="myFunction()";

...or I can use the body tag: ...或者我可以使用body标签:

<body onload="myFunction()">

...or I can even try at the bottom of the page after everything, but the end body or html tag like: ......或者我甚至可以尝试一切后,页面的底部,但最终的bodyhtml标签,如:

<script type="text/javascript">
   myFunction();
</script>

What is a cross-browser(old/new)-compliant method of issuing one or more functions in a manner like jQuery's $.ready() ? 什么是跨浏览器(旧/新)兼容方法,以类似于jQuery的$.ready()的方式发布一个或多个函数?


#1楼

参考:https://stackoom.com/question/fXHI/纯JavaScript等效于jQuery的-ready-页面-DOM准备就绪时如何调用函数-重复


#2楼

Tested in IE9, and latest Firefox and Chrome and also supported in IE8. 在IE9,最新的Firefox和Chrome中测试,并在IE8中也受支持。

document.onreadystatechange = function () {
  var state = document.readyState;
  if (state == 'interactive') {
      init();
  } else if (state == 'complete') {
      initOnCompleteLoad();
  }
}​;

Example: http://jsfiddle.net/electricvisions/Jacck/ 示例: http//jsfiddle.net/electricvisions/Jacck/

UPDATE - reusable version 更新-可重用版本

I have just developed the following. 我刚刚开发了以下内容。 It's a rather simplistic equivalent to jQuery or Dom ready without backwards compatibility. 这与没有向后兼容性的jQuery或Dom相当简单。 It probably needs further refinement. 它可能需要进一步完善。 Tested in latest versions of Chrome, Firefox and IE (10/11) and should work in older browsers as commented on. 已在最新版本的Chrome,Firefox和IE(10/11)中进行了测试,并可以在旧版浏览器中运行,如注释所述。 I'll update if I find any issues. 如果发现任何问题,我会进行更新。

window.readyHandlers = [];
window.ready = function ready(handler) {
  window.readyHandlers.push(handler);
  handleState();
};

window.handleState = function handleState () {
  if (['interactive', 'complete'].indexOf(document.readyState) > -1) {
    while(window.readyHandlers.length > 0) {
      (window.readyHandlers.shift())();
    }
  }
};

document.onreadystatechange = window.handleState;

Usage: 用法:

ready(function () {
  // your code here
});

It's written to handle async loading of JS but you might want to sync load this script first unless you're minifying. 它是为处理JS的异步加载而编写的,但除非您精简,否则您可能要先对其进行同步加载。 I've found it useful in development. 我发现它在开发中很有用。

Modern browsers also support async loading of scripts which further enhances the experience. 现代浏览器还支持脚本的异步加载,从而进一步增强了体验。 Support for async means multiple scripts can be downloaded simultaneously all while still rendering the page. 支持异步意味着可以同时下载多个脚本,同时仍渲染页面。 Just watch out when depending on other scripts loaded asynchronously or use a minifier or something like browserify to handle dependencies. 只需注意何时依赖于异步加载的其他脚本,或者使用缩小器或类似browserify的东西来处理依赖项。


#3楼

I would like to mention some of the possible ways here together with a pure javascript trick which works across all browsers : 我想在这里提及一些可能的方法,以及在所有浏览器中都可以使用的纯JavaScript技巧

// with jQuery 
$(document).ready(function(){ /* ... */ });

// shorter jQuery version 
$(function(){ /* ... */ });

// without jQuery (doesn't work in older IEs)
document.addEventListener('DOMContentLoaded', function(){ 
    // your code goes here
}, false);

// and here's the trick (works everywhere)
function r(f){/in/.test(document.readyState)?setTimeout('r('+f+')',9):f()}
// use like
r(function(){
    alert('DOM Ready!');
});

The trick here, as explained by the original author , is that we are checking the document.readyState property. 正如原始作者所解释的,这里的技巧是我们正在检查document.readyState属性。 If it contains the string in (as in uninitialized and loading , the first two DOM ready states out of 5) we set a timeout and check again. 如果它包含字符串in (如未uninitializedloadinguninitialized 5中的前两个DOM就绪状态开始),我们设置超时并再次检查。 Otherwise, we execute the passed function. 否则,我们执行传递的函数。

And here's the jsFiddle for the trick which works across all browsers. 这是适用于所有浏览器的技巧的jsFiddle

Thanks to Tutorialzine for including this in their book. 感谢Tutorialzine将其包含在他们的书中。


#4楼

The good folks at HubSpot have a resource where you can find pure Javascript methodologies for achieving a lot of jQuery goodness - including ready HubSpot的优秀人才有资源,您可以在其中找到实现许多jQuery优点的纯Javascript方法论-包括ready

http://youmightnotneedjquery.com/#ready 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();
    });
  }
}

example inline usage: 内联用法示例:

ready(function() { alert('hello'); });

#5楼

If you are doing VANILLA plain JavaScript without jQuery, then you must use (Internet Explorer 9 or later): 如果要使用不带jQuery的VANILLAJavaScript ,则必须使用(Internet Explorer 9或更高版本):

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

Above is the equivalent of jQuery .ready : 上面相当于jQuery .ready

$(document).ready(function() {
    console.log("Ready!");
});

Which ALSO could be written SHORTHAND like this, which jQuery will run after the ready even occurs . 哪个还可以像这样简短地编写,哪个jQuery将在ready甚至发生后运行。

$(function() {
    console.log("ready!");
});

NOT TO BE CONFUSED with BELOW (which is not meant to be DOM ready): 不要与以下混淆 (这并不意味着要准备DOM):

DO NOT use an IIFE like this that is self executing: 请勿使用这种会自行执行的IIFE

 Example:

(function() {
   // Your page initialization code here  - WRONG
   // The DOM will be available here   - WRONG
})();

This IIFE will NOT wait for your DOM to load. 该IIFE不会等待您的DOM加载。 (I'm even talking about latest version of Chrome browser!) (我什至在谈论最新版本的Chrome浏览器!)


#6楼

Ready 准备

function ready(fn){var d=document;(d.readyState=='loading')?d.addEventListener('DOMContentLoaded',fn):fn();}

Use like 使用方式

ready(function(){
    //some code
});

For self invoking 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");

});

Support: IE9+ 支持:IE9 +

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值