简体   繁体   中英

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?

To correct this problem use:

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

Out instead of:

$(document).ready(function() {});

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.

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.

If you have jQuery 3.0 and later, use:

 $(window).on("load", function(){ // Do your work });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>

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