Created
April 27, 2011 11:29
-
-
Save louisremi/944086 to your computer and use it in GitHub Desktop.
New defaultDisplay()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var elemDisplays = {}, | |
// Store the iframe outside the function to reuse it | |
iframe, iframeDoc; | |
function defaultDisplay( nodeName ) { | |
if ( !elemDisplays[ nodeName ] ) { | |
// Try the classical method first, which is far faster | |
var elem = document.createElement( nodeName ), | |
display; | |
document.body.appendChild( elem ); | |
display = window.getComputedStyle( elem ) | |
.getPropertyValue( "display" ); | |
document.body.removeChild( elem ); | |
// if the display value is "none", use an iframe | |
if ( display === "none" || display === "false" ) { | |
// No iframe to use yet, so create it | |
if ( !iframe ) { | |
iframe = document.createElement( "iframe" ); | |
iframe.frameBorder = iframe.width = iframe.height = 0; | |
} | |
document.body.appendChild( iframe ); | |
/* Create a cacheable copy of the iframe document on | |
* first call. | |
* IE and Opera will allow us to reuse the iframeDoc | |
* without re-writing the fake html document to it, | |
* Webkit & Firefox won't allow reusing the iframe document | |
*/ | |
if ( !iframeDoc || !iframe.createElement ) { | |
iframeDoc = | |
( iframe.contentWindow || iframe.contentDocument ).document; | |
iframeDoc.write( "<!doctype><html><body></body></html>" ); | |
} | |
elem = iframeDoc.createElement( nodeName ); | |
iframeDoc.body.appendChild( elem ); | |
display = window.getComputedStyle( elem ) | |
.getPropertyValue( "display" ); | |
document.body.removeChild( iframe ); | |
} | |
elemDisplays[ nodeName ] = display; | |
} | |
return elemDisplays[ nodeName ]; | |
} |
You're right, I fixed it. Thanks :-)
As mentioned on Twitter (just moving the discussion here for future reference), <!doctype><html><body>
seems to work just as well.
Thanks Mathias,
You could actually open a pull request on the jquery repository with this simple modification.
Done: jquery/jquery#352
In the latest jQuery-git, display === "false"
has been replaced by display === ""
.
Also, won’t this script still fail when I do stuff like div { display: inline; }
?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Looks like the var declaration for
iframeDoc
isn’t included in this snippet. I don’t think it’s supposed to be global, right?