This is tagged jQuery so I'm giving a jQuery answer for simplicity. This is also solvable in a relatively simple manner without it.
Hooking on every request:
Let's say your method is called myMethod
.
GET/POST
requests may be triggered the following ways:
- Form submits, in which case you can select the form
$("#formID").submit(myMethod);
. Note that if myMethod
returns false it will cause your form to not submit
AJAX
in which case you can use $.ajaxStart
with $.ajaxStart(myMethod)
- "a" tag clicks, and other click handlers, in which case you can perform
$("a[href]").click(myMethod)
, note that this selects all a
tags with an href
attribute, you might want to change the selector to suit your needs
Image
loads which you can handle like explained in this question.
Script
loads which you can detect like explained in this question.
Stylesheet/Link
loads, which is explained in this blog post. You can add a hidden element to the CSS and check if the style was applied in an interval, and when it does call myMethod
What you can't do:
- If your page has a plugin like Flash, or in general anything your JavaScript does not have access to, you can't hook on requests it makes.
The case of displaying a 'loading' gif.
From what you're asking it seems like you only care about image requests, and AJAX requests (correct me if I'm wrong), since external pages that take a long time to load NOT in an AJAX requests can (should) implement that .gif
logic on the new page. This could be handled as I explained above.
Although you can hook every case, I would not do so. I would create a method that loads the 'loading' gif into a place and accepts a url. If that url is an image (for example, by file extension if that's ok with your mapping) use the logic in the image load detect
linked question, if it's AJAX load the loading gif to where the data will be loaded, and replace it with the data on a .done()
handler.
Here is a question about how to do this for an image, here is how to do it for AJAX . The two can be easily combined into a method
which is what I believe you should use.