Iframe preloader animation

Posted by | March 07, 2012 | JavaScript | No Comments

I love working with iframe content loading… noo no way, I actually hate it, but there are situations when loading the content inside the iframe is the only viable technical solution. I am sure you have use it before and maybe you have asked yourself how to add something like a loding animation while the frame is loading. I will provide a example but today I am fling lazy so I will use jQuery, the code should be something like:

 
var ContentLoader = function() {
	function load(url, onContentLoaded) {
 
		$($('#content')).append('<iframe id="myBelovedIframe" frameborder="0" width="500" height="50"></iframe>');
		$('iframe#myBelovedIframe').attr('src', url);
 
		// On iframe content load
		$('iframe#myBelovedIframe').load(function() {
			onContentLoaded(this);
		});
 
	}
 
};
 
c = new ContentLoader();
c.load("http://andreitara.com", function() {
	$('#content').removeClass('loading');
	// TODO Add any code that has to be executed after the frame is loaded
});

This is how the script should look like, and the HTML could be something like:

 
....
<div id="content" class='loading'></div>
...

of course you will need also some CSS for the loading animation like:

 
.loading{
 background-image:url('loading.gif');
}

Your parents should be so proud of you, you first iframe with loading animation :), now you can celebrate.

About Andrei Tara

Andrei is a developer/geek who loves creating high quality and efficient applications, always following the best practices in software engineering. He loves the challenge of learning new, exciting things and playing with new languages, frameworks, and tools.

Leave a Reply