如何在 JavaScript 中检测 document.ready?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3813235/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 02:21:08  来源:igfitidea点击:

How to detect document.ready in JavaScript?

javascriptjquery

提问by Thomas

Possible Duplicate:
$(document).ready equivalent without jQuery

可能的重复:
$(document).ready 等价物,没有 jQuery

I have a framework-less javascript that executes on load:

我有一个在加载时执行的无框架 javascript:

function myJs() {    
   // some code
}
window.load = myJs;

But this causes a delay in the execution of the script. I want to be able to execute this script as soon as the document is ready to be manipulated even before the page has completely finished loading. How can this be done in a cross browser compatible way? In other words how can the:

但这会导致脚本执行延迟。我希望能够在文档准备好在页面完全加载完成之前立即执行此脚本。这如何以跨浏览器兼容的方式完成?换句话说,如何:

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

of jQuery be said in plain JS?

jQuery 可以用纯 JS 表示吗?

回答by Jakob

I have made an implementation (based on the one found in jQuery) that you can use: http://github.com/jakobmattsson/onDomReady/blob/master/ondomready.js

我已经做了一个你可以使用的实现(基于在 jQuery 中找到的):http: //github.com/jakobmattsson/onDomReady/blob/master/ondomready.js

回答by AutoSponge

//old IE
document.onreadystatechange = function() {
   if (this.readyState === "complete"){
      //whatev
   }
};


//for everyone else
document.addEventListener("DOMContentLoaded", function () {
  //whatev
  }, false);

回答by Ryan Kinal

It's actually not that bad. You need a way to add events to document, and the knowledge of what those events should be. Using the standard addEventfunction

其实也没有那么糟糕。您需要一种将事件添加到 的方法document,以及这些事件应该是什么的知识。使用标准addEvent功能

function addEvent( obj, type, fn )
{
 if (obj.addEventListener)
 {
   obj.addEventListener( type, fn, false );
 }
 else if (obj.attachEvent)
 {
  obj["e"+type+fn] = fn;
  obj[type+fn] = function() { return obj["e"+type+fn]( window.event ); };
  obj.attachEvent( "on"+type, obj[type+fn] );
 }
}

You can do the following:

您可以执行以下操作:

// IE
addEvent(document, 'DOMContentLoaded', function() {
    alert('ready');
});

// Other
addEvent(document, 'onreadystatechange', function() {
    if (document.readyState == 'complete')
        alert('ready');
});

// For demonstration purposes, show a 'load' event
addEvent(window, 'load', function() {
    alert('load');
});

The IE event handler will simply not fire in other browsers, and vice-versa.

IE 事件处理程序不会在其他浏览器中触发,反之亦然。

回答by Moses

But this causes a delay in the execution of the script. I want to be able to execute this script as soon as the document is ready to be manipulated even before the page has completely finished loading.

但这会导致脚本执行延迟。我希望能够在文档准备好在页面完全加载完成之前立即执行此脚本。

Well there are three ways you can approach this problem:

那么有三种方法可以解决这个问题:

  1. As a few have already suggested, you can draw inspiration from the jQuery source code and integrate that into your script. (I recommend watching Paul Irish on jQuery Sourceand looking at JS Libs Deconstructed.
  2. You can put the function call at the end of the body tag instead of in the head tag. This allows for all DOM elements to be loaded before the script starts.
  3. If you don't need to work with the DOM whatsoever, you could just make it a self-executing function so you don't have to wait for anything. (function startNow(){}())
  1. 正如一些人已经建议的那样,您可以从 jQuery 源代码中汲取灵感并将其集成到您的脚本中。(我建议在 jQuery Source 上观看Paul Irish并查看JS Libs Deconstructed
  2. 您可以将函数调用放在 body 标签的末尾,而不是放在 head 标签中。这允许在脚本启动之前加载所有 DOM 元素。
  3. 如果您不需要使用任何 DOM,您可以将其设为自执行函数,这样您就不必等待任何事情。 (function startNow(){}())

回答by Shikiryu

Put

function myJs() {    
   // some code
}

in the <head></head>and

<head></head>

window.load = myJs;

Just before </body>

就在之前 </body>

回答by Fribu - Smart Solutions

you can create a function where ever you wont, the call it in

你可以在任何你不想的地方创建一个函数,调用它

`<body onLoad="function();">`