Skip to content

Instantly share code, notes, and snippets.

@jcayzac
Created March 28, 2012 09:19
Show Gist options
  • Save jcayzac/2224992 to your computer and use it in GitHub Desktop.
Save jcayzac/2224992 to your computer and use it in GitHub Desktop.
Responsive loading of iframes (e.g. youtube embeds)
<h1>This is loaded only after the DOM is ready, if JS is supported</h1>
<p>Loading the iframe normally would block until the iframe's own DOM is ready, resulting in slow loading times. Non-Javascript browsers get normal (inefficient) behaviour.</p>
<!-- note: on JS-enabled browsers, the noscript element will get replaced by its content (keep that in mind for CSS) -->
<noscript class="noblock">
<iframe src="https://www.youtube-nocookie.com/embed/g2FOLrC2e6E?wmode=opaque&amp;vq=hd720&amp;autohide=1&amp;fs=1&amp;iv_load_policy=3&amp;loop=1&amp;rel=0&amp;showsearch=0&amp;showinfo=0&amp;modestbranding=1"></iframe>
</noscript>
// in your DOMContentLoaded handler:
Array.prototype.forEach.call(document.querySelectorAll("noscript.noblock"), function(noscript) {
var parent = noscript.parentElement || noscript.parentNode,
div = document.createElement("div")
div.innerHTML = noscript.innerText || noscript.textContent
while (typeof div.childNodes[0] !== "undefined")
parent.insertBefore(div.removeChild(div.childNodes[0]), noscript)
parent.removeChild(noscript)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment