2017-02-05 #jquery

jQuery: A Guide to Handling iFrame Loading Events

Recently I've had a project that needed to do some work in JavaScript on code within an iframe. The problem I was facing was that the website inside the iframe will take a lot longer to load than the page that loads the JavaScript. Normally when working with jQuery you would wrap your code or your init function around a document ready function so the code will only run when the website loaded.

$( document ).ready(function() {
    console.log( "Webpage is ready!" );

But I couldn't use this approach in this situation as the iframe site hasn't loaded yet it would mean the jQuery will fail because it can not find the selectors inside the iframe. Therefore I needed to find a way of waiting for the iframe to load and then trigger and event on the parent page to start the jQuery code. In a previous tutorial I wrote about the jQuery load() method and using this to call a script and do something after that script is ran.

// load the RSS feed into the #feed_result element

While researching this problem I found that you can use the load function on an iframe to trigger a load event when the page has complete. All we need to do is use on method triggering the load event on the ID of the iframe. First add an ID to the iframe HTML.

<iframe id="iframe-id" src="" frameborder="0" width="100%" height="900"></iframe>

Then use the on method on this iframe triggering the load event when the iframe is fully loaded.

$('#iframe-id').on( 'load', function() {
    // code will run after iframe has finished loading
} );


Reliable uptime monitoring and instant alerts for any website downtime.

Get 50% off forever using the code 50OFFUP.