jQuery/javascript check if anything is loading

1.5k views Asked by At

Once a document is fully loaded, my javascript starts changing things like img sources and background images. These changes happen in different ways (by preloading them in JS or by directly changing the src attribute for exemple). However, for these changes new files need to be loaded. These changes happen randomly, with random sources to random elements, so I can't provide a list of elements or sources.

At certain moments in time, my javascript (jQuery) needs to check if anything is still loading, or if everything is completely loaded.

In other words, I need a way to check if any network traffic is going on or not.

Ideally, I wan't a way to set the variable loading to true every time a request is being made to load a file, and to set that variable to false ones the loading process if complete, so I can use something like while (loading==true) {loopscript()} to loop some script while loading.

Is there any jQuery way to do this?

2

There are 2 answers

6
volatilevar On

You can use the JQuery load event, but you will need to make sure the setInterval call is embedded in the head. The below example is to load a page with an image taking 5000ms to load. It output to the console every 1000ms.

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
  <script>
  var intervalID = setInterval(function() {
    console.log("loading");
  }, 1000);
  </script>
</head>
<body>
  <script>
  jQuery(window).load(function() {
    clearInterval(intervalID);
  });
  </script>
  <img src="http://deelay.me/5000/http://deelay.me/img/5000ms.gif">
</body>

0
charlietfl On

You could create a promise for each action using $.Deferred and push all the promises to array.

Then use $.when() to update the loading variable after all the promises have resolved.

Each individual promise would need to be resolved within a load event handler for images or whatever other event might be triggered when that action is completed