Programming

Show spinner GIF during an http request in AngularJS

19 September 2026 · 9 min read

Show spinner GIF during an http request in AngularJS

In the dynamic world of web development, user experience is paramount. One critical aspect of a seamless user experience is providing visual feedback during asynchronous operations, such as HTTP requests. When working with AngularJS, a popular JavaScript framework for building web applications, effectively managing these requests is essential. Learning how to show spinner GIF during an $http request in AngularJS is a fundamental skill. Users don’t want to stare at a blank screen, wondering if anything is happening. A spinner GIF provides a visual cue, assuring them that the application is processing their request. This simple addition can significantly improve perceived performance and reduce user frustration, leading to a more engaging and satisfying application experience. By implementing a loading indicator, you acknowledge the user’s action and manage their expectations, preventing them from prematurely abandoning the process or resubmitting the same request multiple times. This guide will walk you through the steps to effectively implement a spinner GIF during your AngularJS $http requests.

Understanding AngularJS $http Requests and User Experience

AngularJS’s $http service is the cornerstone for making HTTP requests to backend servers. It allows your application to fetch data, submit forms, and perform various other server-side interactions. However, these requests can take time, depending on network conditions and server load. Without visual feedback, users may perceive the application as unresponsive, leading to a negative user experience. The key is to provide immediate feedback when a request is initiated and remove it once the request completes successfully or encounters an error. This is where the spinner GIF comes in. Displaying a spinner informs the user that the application is actively working on their request. According to a study by Nielsen Norman Group, “Users often abandon tasks if they perceive delays, even if the actual delay is minimal.” Nielsen Norman Group - Response Times This highlights the importance of providing timely feedback during asynchronous operations.

Consider a scenario where a user submits a form on your AngularJS application. Without a spinner, they might click the submit button multiple times, thinking the first click didn’t register. This can lead to duplicate submissions and data inconsistencies. Implementing a spinner GIF prevents this by clearly indicating that the form submission is in progress. The spinner should be displayed immediately after the submit button is clicked and hidden once the server confirms the successful submission or returns an error. Proper error handling is also crucial. If the request fails, the spinner should be hidden, and an appropriate error message should be displayed to the user. This provides a complete feedback loop, ensuring a smooth and informative user experience.

Furthermore, using a spinner GIF aligns with accessibility best practices. It provides a visual cue for users who may have difficulty perceiving other types of feedback, such as subtle changes in the application’s state. By incorporating a spinner, you make your application more inclusive and accessible to a wider range of users. To enhance accessibility, consider adding ARIA attributes to the spinner element, such as aria-busy="true", to further communicate the loading state to assistive technologies.

Implementing a Spinner GIF Using AngularJS Interceptors

AngularJS interceptors provide a powerful and centralized way to manage HTTP requests and responses. They allow you to intercept and modify requests before they are sent and process responses before they are delivered to your application. This makes them an ideal mechanism for implementing a spinner GIF across all your $http requests. By creating an interceptor, you can automatically display the spinner before each request and hide it after the request completes, without having to manually manage the spinner visibility in each individual controller. This approach promotes code reusability and reduces the risk of errors.

The interceptor works by listening to the request and response events of the $http service. When a request is intercepted, the interceptor displays the spinner GIF. When a response is received (either successful or an error), the interceptor hides the spinner. This ensures that the spinner is always displayed while the request is in progress and hidden when the request is complete. The following snippet is optimized for the featured snippet:

To show a spinner GIF during an $http request in AngularJS, use interceptors. Interceptors allow you to intercept and modify HTTP requests and responses globally. By creating an interceptor, you can display the spinner before each request (in the request method) and hide it after the request completes (in the response and responseError methods). This centralized approach ensures consistency and reduces code duplication.

Here’s how you can implement a spinner GIF using AngularJS interceptors:

  1. Create an interceptor factory.
  2. Define the request method to show the spinner.
  3. Define the response and responseError methods to hide the spinner.
  4. Register the interceptor with the $httpProvider.

Code Example: AngularJS Interceptor for Spinner GIF

Let’s look at a code example to illustrate how to implement the interceptor. First, you need to define a service or a variable to control the visibility of the spinner. This service will be used by the interceptor to show and hide the spinner. Then, you create the interceptor factory, which includes the request, response, and responseError methods. These methods will be called automatically by AngularJS whenever an HTTP request is initiated or completed. Finally, you register the interceptor with the $httpProvider to make it active.

Here’s a sample code snippet:

javascript angular.module(‘myApp’) .config([’$httpProvider’, function($httpProvider) { $httpProvider.interceptors.push(‘spinnerInterceptor’); }]) .factory(‘spinnerInterceptor’, [’$q’, ‘$rootScope’, function($q, $rootScope) { $rootScope.loading = false; // Initialize loading state return { request: function(config) { $rootScope.loading = true; // Show spinner return config; }, response: function(response) { $rootScope.loading = false; // Hide spinner return response; }, responseError: function(rejection) { $rootScope.loading = false; // Hide spinner return $q.reject(rejection); } }; }]); In this example, $rootScope.loading is used to control the visibility of the spinner. You can bind this variable to a spinner element in your HTML using ng-show or ng-if. Remember to include the necessary AngularJS modules and dependencies in your application. To learn more about AngularJS interceptors, refer to the official AngularJS documentation. AngularJS $http Service Documentation The code above provides a basic implementation. You can customize it further to handle specific scenarios, such as excluding certain requests from displaying the spinner or adding a delay before showing the spinner.

Advanced Techniques and Considerations

While the basic implementation using interceptors is effective, there are several advanced techniques and considerations to keep in mind for more complex applications. For example, you might want to exclude certain requests from displaying the spinner, such as requests to static assets or requests that are known to be very fast. You can achieve this by adding a configuration option to the request and checking this option in the interceptor. Another consideration is handling multiple concurrent requests. In this case, you need to keep track of the number of active requests and only hide the spinner when all requests have completed.

Here are some key points to consider:

  • Request Exclusion: Implement logic to exclude specific requests from triggering the spinner.
  • Multiple Requests: Manage the spinner state based on the number of active HTTP requests.

Another important aspect is optimizing the spinner GIF itself. Use a lightweight GIF to minimize the impact on page load time. Consider using CSS-based spinners for better performance and customization options. Furthermore, ensure that the spinner is visually appealing and consistent with your application’s design. A well-designed spinner can enhance the user experience and make the application feel more polished. You should also test the spinner implementation thoroughly across different browsers and devices to ensure that it works correctly in all environments. Remember that even small details can have a significant impact on the overall user experience. Optimizing your AngularJS application will improve performance. Enhance user experience.

Here are some best practices for spinner implementation:

  • Use a lightweight spinner GIF or CSS-based spinner.
  • Ensure the spinner is visually appealing and consistent with your application’s design.
  • Test the implementation thoroughly across different browsers and devices.

FAQ: Showing Spinner GIF During AngularJS $http Requests

Why should I show a spinner GIF during an $http request?
Showing a spinner GIF provides visual feedback to the user, indicating that the application is processing their request. This improves the user experience by preventing them from perceiving the application as unresponsive.
How do I implement a spinner GIF in AngularJS?
You can implement a spinner GIF using AngularJS interceptors. Interceptors allow you to intercept and modify HTTP requests and responses globally, making it easy to show the spinner before each request and hide it after the request completes.
What are some advanced techniques for spinner implementation?
Advanced techniques include excluding certain requests from displaying the spinner, handling multiple concurrent requests, and using CSS-based spinners for better performance.
What are the benefits of using CSS-based spinners?
CSS-based spinners offer better performance and customization options compared to GIF images. They are also more responsive and adapt better to different screen sizes.
Can I customize the spinner's appearance?
Yes, you can customize the spinner's appearance using CSS. This allows you to match the spinner's design to your application's overall look and feel.
Implementing a spinner GIF during AngularJS $http requests is more than just a cosmetic enhancement. It's a fundamental aspect of creating a positive and engaging user experience. By using interceptors, you can easily manage the spinner's visibility across your entire application, ensuring that users are always informed about the status of their requests. Remember to optimize the spinner's design and performance, and consider advanced techniques to handle complex scenarios. Always prioritize user feedback and iterate on your implementation to continuously improve the user experience. Now that you've learned the basics, experiment with different spinner styles, explore advanced techniques, and create a seamless experience for your users. Remember to test across different browsers and devices to ensure compatibility and a consistent user experience for everyone.

Question & Answer :
I am using the $http service of AngularJS to make an Ajax request.

How can a spinner GIF (or another type of busy indicator) be shown while the Ajax request is executing?

I don’t see anything like an ajaxstartevent in the AngularJS documentation.

This really depends on your specific use case, but a simple way would follow a pattern like this:

.controller('MainCtrl', function ( $scope, myService ) { $scope.loading = true; myService.get().then( function ( response ) { $scope.items = response.data; }, function ( response ) { // TODO: handle the error somehow }).finally(function() { // called no matter success or failure $scope.loading = false; }); }); 

And then react to it in your template:

<div class="spinner" ng-show="loading"></div> <div ng-repeat="item in items>{{item.name}}</div>