Search code examples
jqueryajaxjquery-load

jQuery $.load() sends a GET request multiple times


There's some code that looks like this:

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

Periodically, on production, the GET request is being sent multiple times. I can see this using a packet sniffer.

This isn't reproducible locally.

There's a couple of similar questions on here but they don't seem to be much use.

What I'd like to know is:

  • Why does the function sendAGetRequest() get called multiple times?
  • What sort of things could cause this to only happen on production and not local?

I suspect the problem to be $(window).load and am considering changing this to $(document).ready. Is that a good call? As I said, I can't reproduce the problem locally and I wouldn't want to upload something to live without knowing whether it might actually fix things or not.


Solution

  • $(window).load will only be triggered when page is fully loaded including pictures. While $(document).ready will be triggerred when the whole DOM is ready. This is a much better point to trigger such request as you don't have to wait for the whole resources to be loaded. i am not sure why the function is called multiple times, although in theory it shouldn't.