elem.ownerDocument.defaultView breaks when elem == (iframe) document
in the core function curCSS (around line 4691 in jquery-1.4.2.js) jQuery attempts to access the defaultView attribute from elem.ownerDocument. This is fine and well, except for the relatively complex case where you are loading jQuery outside of an iframe, and then are trying to use jQuery from within the iframe without reloading it. There is a good reason for having a setup like this (in short, to enable an "load once - always on" connection to a server, and then using hashchanges to navigate the site, setting the content of a 100% iframe), so that's not really the point of this discussion. The problem occurs when you attempt to, e.g., add jQuery UI stuff to elements within the iframe. jQuery.curCSS runs from the element all the way up to the iframe document, but unlike the normal document, where it would stop before getting to it, jQuery tries to run curCSS on the iframe document as well. Attempting to do:
- var defaultView = elem.ownerDocument.defaultView
breaks when elem is the iframe document, as document.ownerDocument is null. As the ownerDocument property is read-only, there is no way to fool jQuery, e.g., by doing a
- myIFrame.document.ownerDocument = myIFrame.document
By simply adding an extra condition like:
- var ownerDocument = elem.ownerDocument || elem
- var defaultView = ownerDocument.defaultView
everything would work fine, as the next line checks whether there is a defaultView:
- if ( !defaultView ) {
- return null;
- }
I know my setup isn't necessarily standard, but it makes sense to allow it (as I don't want to load jQuery each time the iframe content changes, I want to load it once, when the outer framewrapper page loads, and then have the inner iframe have access to jQuery). This change could only be considered good practice, as it verifies an object is there before attempting to access its attributes. A slightly better version of the change would be something like:
- var ownerDocument = elem.ownerDocument;
- if ( !ownerDocument) {
- return null;
- }
- var defaultView = ownerDocument.defaultView;
- if ( !defaultView ) {
- return null;
- }
This would function the same, as document.defaultView is null anyhow, so you don't really need the first conditional, but this version of the fix wouldn't rely on that fact, and would instead explicitly check that there is an elem.ownerDocument before proceeding.
Anyhow, I hate the idea of having a custom/hacked version of jQuery, and see no reason why this fix shouldn't be included in the official jQuery source, so how do we go about doing this?