Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery behaving strange after page refresh (F5) in Chrome

I have a script, that works fine in FireFox, IE, but not in Chrome after F5 refresh only! It does work in chrome, if I focus the url address and click enter, but it doesnt work if I press F5, I don't get it at all, how can this have an effect on the jQuery code.

So here's the script:

$(document).ready(function() {
    var width = 0;
    $('#gallery img').each(function() {
    width += $(this).outerWidth(true);
    });

    $('#offer #gallery').css('width', width + 'px');
});

And the result of Width should be 820, but I only get this if I refresh the site by focusing the url address and clicking enter, otherwise it gives the result of 90.

I tryed restarting browser and deleting cache, so the problem isn't there, any ideas?

like image 266
Mike Avatar asked Jun 28 '11 10:06

Mike


3 Answers

To correct this problem use:

$(window).load(function() {});

Out instead of:

$(document).ready(function() {});
like image 77
matheusvmbruno Avatar answered Nov 09 '22 02:11

matheusvmbruno


I'd guess that this happens because the images have not yet been loaded when the ready() event is triggered, and 18px is the size of the placeholder icon for images. Pressing F5 causes all resources in the page to be reloaded, while normal navigation does not.

You could try replacing the ready() call with a load() call, or supplying width and height attributes in your img tags so that their size is known before the images are loaded.

From JQuery API for .load():

The load event is sent to an element when it and all sub-elements have been completely loaded.

And from .ready():

While JavaScript provides the load event for executing code when a page is rendered, this event does not get triggered until all assets such as images have been completely received. In most cases, the script can be run as soon as the DOM hierarchy has been fully constructed.

like image 44
vehnae Avatar answered Nov 09 '22 04:11

vehnae


I had a similar problem trying to call a custom js library. I was also using a combination of jquery and jquerymobile.

Both $(window).load(function() {}); and $(document).ready(function() {}); were failing. Using:

$(document).on("pageinit", function () {});

solved my case.

like image 1
isgarci Avatar answered Nov 09 '22 02:11

isgarci