Monday, May 1, 2017

Using setInterval to run a script after element is finished loading from server

Sometimes I need to run a JS script on a set of HTML elements, but I run into problems when the script fires before elements or assets are finished loading from the server side.

For example, let's say I'm loading a grid of items, each of which has an image and some copy underneath. I want each item in the grid to be the same height, regardless of how much text it has. Generally I'd run a JS script to set the heights of all the items to the height of the tallest item.

However, since I'm loading the images through a CMS off the server, it sometimes takes a little bit before they are all loaded. If I run the script normally, it will fire before all the images finish loading, and it will resize the items to a height that is too short.

I've found that using the javascript function "setInterval" is a good solution; it runs at a frequency of your choosing, and each time it checks if the slower-loading element is loaded. If it isn't loaded, it will simply repeat the function; if the element is found to be finished loading, then it will run another JS script of your choosing, and clear the interval to stop checking.



// create your interval function as a named variable; having a name allows you to clear it later
var checkImages = setInterval(function () {

    // This checks the height of the last grid item's image, since it will be loaded last. 
    // Once it's loaded, the height will be more than 0.
    if ($('.grid:last img').height() > 0) {

        // if the image is done loading, clear out the interval
        clearInterval(checkImages); 
        
        // then run the script you want; this just happens to be the one I'm using
        equalizeHeights($('.grid__item')); 
    }
    else {
    }
}, 200); // run this every 200 ms

No comments:

Post a Comment