开发者

Running jQuery function after all media is loaded

开发者 https://www.devze.com 2023-03-12 05:51 出处:网络
I have a simple jQuery script which pushes the footer to the bottom of the page, even if the content is not long enough:

I have a simple jQuery script which pushes the footer to the bottom of the page, even if the content is not long enough:

$(document).ready(function(){
    positionFooter();
    function positionFooter(){
        //get the div's padding
        var padding_top = $("#footer").css("padding-top").replace("px", "");
        //get the current page height - the padding of the footer
        var page_height = $(document.body).height() - padding_top;
        var window_height = $(window).height();
        //calculate the difference between page and window height
        var difference = window_height - page_height;
        if (difference < 0) 
            difference = 0;
        //write the changes to the div
        $("#footer").css({
            padding: difference + "px 0 0 0"
        })
    }
    //re-run the function if browser window is resized
    $(window).resize(positionFooter)
});

Unfortunately the (document).ready trigger is to early and dose not consider image & font loading, so the value that is calculated is incorrect. Is there a trigger that is suited for this kind of tasks?

Also the site I'm building is using Disqus fot comments, which also changes the page length again, though I开发者_StackOverflow中文版 think I need a call-back from the Disqus script to take that change into consideration.


try $(window).load()

You may also want to check the jQuery documentation on the different document loading events: http://api.jquery.com/category/events/document-loading/

Hope it helps


See this answer: Official way to ask jQuery wait for all images to load before executing something


Although it's fairly easy to do with pure CSS, the following tweak on the last line should help with the initial load:

    $(window).resize(positionFooter).resize();
});

It's also recommended to use the resize event handler with a throttler which is pretty easy to implement. Include the extra bit of JS and change that same chunk of code to this:

    $(window).resize($.throttle(250, positionFooter)).resize();
});


I wonder if using the doms' window.onload might be a better solution. I think that will wait for the media to load.


You can execute this in pure CSS using the sticky footer technique.

http://www.cssstickyfooter.com/

0

精彩评论

暂无评论...
验证码 换一张
取 消