質問

I am using the following approach to Preload the content of my website:

$(window).load(function(){
    $('#preLoader').hide();
    $('#container').show();
});

Now my #container div contains all my website content. I don't want this to be shown until my body background image has completely loaded...So while the background image is loaded, the #preLoader div displays with an animated loader gif inside.

The issue:

There are some elements that do not always load (eg gravatars) due to the Server containing the resource not being available...so the $(window).load() function never executes since the page has not finished loading - it it stuck at trying to download a resource that is not available and keeps displaying the loader.

How do I ignore requests that takes too long to respond so that my load function can execute - hide the loader and show the content.

I do not want to use the $(document).ready() function, since it does not wait until my background image has finished loading...

役に立ちましたか?

解決

If you're just trying to preload the background image, you could do something like this:

$(document).ready(function() {
    $('#preLoader').show();
    $('#container').hide();

    $('<img>', {src: '/url/of/image.jpg'}).load(function() {
        $('#preLoader').hide();
        $('#container').show();
    }).error(function() {
        // Something went wrong
    });
});

A better alternative would be to use the waitForImages plugin:

$(document).ready(function() {
    $('#preLoader').show();
    $('#container').hide();

    $(document).waitForImages(function() {
        $('#preLoader').hide();
        $('#container').show();
    });
});

他のヒント

You should try some trick. Make change in your page source for all elements like gravatar:

<img data-src="http://some-very-busy-resource.org/avatar.jpg" />

See, it is no "src" attribute presents, browser definetly doesn't load this image and page loads fast, you script shows the body as you expect.

Then, to load ignored images add this code:

   $('body').find('img').each(function(){
        src = $(this).data('src');

        if ('undefined' !== typeof src) {
            $(this).attr('src', src);   
        }
    });

So, new script should be like next:

$(function(){
    $('#preLoader').hide();
    $('#container').show();
    $('body').find('img').each(function(){
        src = $(this).data('src');
        if ('undefined' !== typeof src) {
            $(this).attr('src', src);   
        }
    });
});
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top