Skip to content

Instantly share code, notes, and snippets.

@jimmynotjim
Created September 14, 2012 19:04
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jimmynotjim/3724006 to your computer and use it in GitHub Desktop.
Save jimmynotjim/3724006 to your computer and use it in GitHub Desktop.
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.

http://css-tricks.com/snippets/jquery/display-loading-graphic-until-page-fully-loaded/

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

http://www.ajaxload.info/

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>
</div>

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

@rsmithlal
Copy link

Thanks! This a handy reference.

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