Last active
July 23, 2016 19:38
-
-
Save Comandeer/abf67165097d51b63875 to your computer and use it in GitHub Desktop.
Better document.write
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
( function( doc ) { | |
'use strict'; | |
var createFragment = ( function( template ) { | |
// http://stackoverflow.com/a/25214113 | |
if ( template ) { | |
return function( html ) { | |
var elem = document.createElement( 'template' ); | |
elem.innerHTML = html; | |
return elem.content; | |
}; | |
} | |
// http://stackoverflow.com/a/9285046 | |
else { | |
return function( html ) { | |
var elem = document.createElement( 'div' ), | |
frag = document.createDocumentFragment(), | |
child; | |
elem.innerHTML = html; | |
while ( child = elem.firstChild ) { | |
frag.appendChild( child ); | |
} | |
return frag; | |
} | |
} | |
} ( 'content' in document.createElement( 'template' ) ) ), | |
lastInserted, | |
lastParent; | |
doc.write = function( html ) { | |
var script = document.currentScript, | |
frag = createFragment( html ); | |
// Probably jQuery Ajax request. | |
if ( !script ) { | |
// Assumes jQuery $.get. | |
var scripts = document.getElementsByTagName( 'script' ), | |
regex = new RegExp( 'document\\.write\\([\'"]' + html + '[\'"]\\)' ), | |
i = 0, | |
tmp; | |
while ( tmp = scripts[ i++ ] ) { | |
if ( regex.test( tmp.innerHTML ) ) { | |
script = tmp; | |
} | |
} | |
} | |
if ( script && script.parentNode ) { | |
lastInserted = frag; | |
lastParent = script.parentNode; | |
return script.parentNode.replaceChild( frag, script ); | |
} | |
else { | |
if ( lastParent && lastInserted ) { | |
return lastParent.insertBefore( frag, lastInserted.nextSibling ); | |
} else { | |
document.body.appendChild( frag ); | |
} | |
} | |
} | |
} ( document ) ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment