Does the jQuery $(window).load(); event not fire on pages without a <!DOCTYPE> declaration? (…in a chrome extension content script)

前提是你 提交于 2019-12-23 08:00:03

问题


I'm working on a Google Chrome extension that manipulates a webpage, but after it is either partially loaded (the DOM) or fully loaded (with images).

It seems that many sites nowadays use the

<!DOCTYPE html>

declaration, or some variation of it, but many others do not. The question is mainly about HTML doctypes...I'm not sure about the others.

Is it safe to assume that if a webpage does not have the DOCTYPE declaration, then $(window).load(); will not be fired?

In the beginning I was using $(document).ready(); (for when the DOM is loaded), but later switched to $(window).load(); (to let the images load too).

The thing is, now $(window).load(); does not seem to work if there is no DOCTYPE. $(document).ready(); seems to work on all pages, regardless of whether a DOCTYPE is declared or not.

Maybe this can be useful for others with this same issue. I searched a bit and didn't find a decisive answer. It seems that I will end up using something like this:

if (window.document.doctype != null) {$(window).load(checkEntries);}
if (window.document.doctype == null) {$(document).ready(checkEntries);}

I guess my question is... Is this normal to have to check for the DOCTYPE to know which event to use? Or am I missing something here?

Basically, why does $(window).load(); seem not to fire if there's no DOCTYPE declaration?


回答1:


Basically, you shouldn't be using $(window).load(), since it's not fully supported. If you really need it, then your solution above is the best you can do. The jQuery page sums up the caveats nicely:

Caveats of the load event when used with images

A common challenge developers attempt to solve using the .load() shortcut is to execute a function when an image (or collection of images) have completely loaded. There are several known caveats with this that should be noted. These are:

  • It doesn't work consistently nor reliably cross-browser
  • It doesn't fire correctly in WebKit if the image src is set to the same src as before
  • It doesn't correctly bubble up the DOM tree
  • Can cease to fire for images that already live in the browser's cache

URL: http://api.jquery.com/load-event/




回答2:


The .ready() method is generally incompatible with the <body onload=""> attribute. If load must be used, either do not use .ready() or use jQuery's .load() method to attach load event handlers to the window or to more specific items, like images.



来源:https://stackoverflow.com/questions/13231768/does-the-jquery-window-load-event-not-fire-on-pages-without-a-doctype-d

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!