[How to] Global progress indicator for ajax requests in jQuery


Showing a loading icon (like the one below) when an ajax request is running is a common practise to ensure end-user is aware that page/information is being updated in background.

ajax loader icon

While developing large scale web applications where one might have numerous ajax requests in the code, it might result in duplication of code to show and hide the loader for each and every ajax request individually.

Instead of writing the code to display and hide the loader for every ajax request, you can add the code below to your layout (common file included in all pages, e.g. footer). But if you do not have a common layout then the code above won’t help you since you’ll end up copy pasting the same code in all files individually which would result in same issue (code duplication) that we are trying to overcome here 🙂

Assuming “loader” is the ID of icon/image (or parent element), you can use the code below.

This would not only save some amount of time which could be utilised for other productive things, it would also help in avoiding unnecessary code duplication. You can use these handlers for anything other than showing/hiding loader as well.

Note that if you are making the ajax request with global option set to false then ajaxStart and ajaxStop events wouldn’t fire. By default global is set to true so you can actually use the global option to control for which requests you would like to show the loader icon. If you do not want to show the loader for a specific ajax request then set global to false. For example,

There are some other global ajax event handlers in jQuery you can refer to see if they suit your use case(s) better.

Happy coding!!!