Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Use Modernizr and jQuery to show a loading gif while an iframe loads

Hat toss to CSS Tricks for setting me on the right track using Modernizr to check if js is enabled or not to avoid permanently hiding the iframe from non-js users.

Also much love to Ajax Load for the custom colored loading gif.

First, set up your html for a container, image and iframe

<div class="frame_container">
	<img src="loading.gif" class="loading" />
	<iframe id="my_iframe" src="[some url]"></iframe>

Next style your elements. I'm using .no-js and .js that are provided by Modernizr on the html element to avoid showing the image and hiding the iframe on browsers w/ javascript turned off, very important for usability. Next I set the container to position: relative and the image to position: absolute while centering it in the container.

.no-js .loading {
	display: none;
.js .loading {
	display: block;
	left: 150px;
	position: absolute;
	top: 300px;
.js #my_iframe {
	visibility: hidden;
.frame_container {
	position: relative;

Last is my script that watches for the iframe to finish loading, then swaps out the loading img for the iframe.

$('#my_iframe').load(function() {
	$('.loading').css('display', 'none');
	$('.js #my_iframe').css('visibility', 'visible');

I used visibility for the iframe instead of display because I didn't want the container or other elements on the page shifting around after the switch. If you are setting your container to a specific size you could use display instead

Copy link

rsmithlal commented Aug 10, 2016

Thanks! This a handy reference.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment