简体   繁体   中英

How to load page only after JavaScript function has finished executing and performed its magic?

Here's the story...

I have an image that is of dimensions 1174px x 660px within a container of dimensions 1174px x 375px. The image's height is cutoff and only 375 pixels worth of the image's height is displayed as I set overflow hidden on the container.

I have created a JavaScript function that takes this image (1174x660) and vertically centers it in its container (1174x 375) so that the center of the image is at the center of the container.

function allFeaturesImagesResize () {
    var allFeatures = function () {
        var image = $('.all-features article img'),
            container = $('.all-features article'),
            container_height = container.height(),
            image_height = image.height(),
            container_center = .5 * container_height,
            image_center = .5 * image_height,
            center = (image_center - container_center);
            image.css('position','relative').css('bottom', center);

    }
    $(function () {
        $(window).resize(function () {
            allFeatures();
        }).resize();
    });
}

I am using a $(document).ready(function() { //... }); wrapper around this function, however, whenever the page loads I can see the function doing its work of moving the image up to the center point. Is there any way to delay the pay load until after this repositioning is complete?

Keep in mind my site is fluid responsive which is why I need to dynamically position the images as I don't know the user's viewport beforehand dimensions (specifically the width).

Use load instead of ready event. $(window).load(function(){ ... your code } will tell that the code should be executed only after all images are loaded. ready event will be fired when the DOM is loaded even if the images are not finished loading

Note that you are selecting multiple images $('.all-features article img') . By doing images.height() it will only get the height of the first found image. The same for the line that select multiple container.

Your code should be translate into "For each image found do" : $('.all-features article img').each (function(){...});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM