当页面DOM加载(但在window.onload之前)时收到通知 [英] Getting notified when the page DOM has loaded (but before window.onload)

查看:144
本文介绍了当页面DOM加载(但在window.onload之前)时收到通知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道有一些方法可以在页面正文加载时收到通知(在所有图像和第三方资源加载之前都会触发 window.onload 事件),但是每个浏览器都有所不同



在所有浏览器上都有确定的方法吗?



到目前为止,我知道:




  • DOMContentLoaded :在Mozilla,Opera 9和最新的WebKits上。这涉及到向事件添加一个监听器:



    document.addEventListener(DOMContentLoaded,[init function],false);


  • 延迟脚本:在IE上,您可以发送一个带有@defer属性的SCRIPT标签,只有在BODY标签关闭后才能加载。


  • 轮询:在其他浏览器上,您可以继续进行投票,但是甚至有一个标准的投票方式,还是需要做不同的每个浏览器上的东西?




我想要没有使用document.write或外部文件。



这可以通过jQuery完成:

  $ ).ready(function(){...})

但是,我正在写一个JS图书馆,不能指望jQuery总是存在。

解决方案

没有跨浏览器的方法来检查DOM是否准备就绪 - 这就是图书馆喜欢的原因jQuery存在,抽象出一些令人讨厌的一些不兼容的东西。



Mozilla,Opera和现代WebKit支持 DOMContentLoaded 事件。 IE和Safari需要奇怪的黑客,如滚动窗口或检查样式表。 gory细节包含在jQuery的 bindReady()函数中。


I know there are some ways to get notified when the page body has loaded (before all the images and 3rd party resources load which fires the window.onload event), but it's different for every browser.

Is there a definitive way to do this on all the browsers?

So far I know of:

  • DOMContentLoaded : On Mozilla, Opera 9 and newest WebKits. This involves adding a listener to the event:

    document.addEventListener( "DOMContentLoaded", [init function], false );

  • Deferred script: On IE, you can emit a SCRIPT tag with a @defer attribute, which will reliably only load after the closing of the BODY tag.

  • Polling: On other browsers, you can keep polling, but is there even a standard thing to poll for, or do you need to do different things on each browser?

I'd like to be able to go without using document.write or external files.

This can be done simply via jQuery:

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

but, I'm writing a JS library and can't count on jQuery always being there.

解决方案

There's no cross-browser method for checking when the DOM is ready -- this is why libraries like jQuery exist, to abstract away nasty little bits of incompatibility.

Mozilla, Opera, and modern WebKit support the DOMContentLoaded event. IE and Safari need weird hacks like scrolling the window or checking stylesheets. The gory details are contained in jQuery's bindReady() function.

这篇关于当页面DOM加载(但在window.onload之前)时收到通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆