Creating a Reusable Page Loader using JavaScript Tutorial

In this tutorial, you will learn how to Create a Reusable Page Loader using JavaScript. The tutorial aims to provide IT/CS students and new programmers with a reference for using JavaScript to develop creative web applications. Here, snippets and a sample web application source code are provided to give you a better idea of how to achieve the goal of this tutorial.

What is a Page Loader?

A Page Loader is a component of a web page that is commonly used to show or display a loading page overlay when navigating, form submission, etc. This component is usually shown with spinners or progress/loading bars. Developers are implementing this kind of component in a web application to let their end-user know that an action, modification, etc are being processed either backend or in the frontend that they must wait before continuing of using the application.

How to Create a Reusable Loader using JavaScript?

Creating a Page Loader in a web application is not that so complicated to achieve. Using a short line of codes using JavaScript, we can create a simple function that triggers the loader to be shown or displayed on the page document. Using CSS (Cascading Stylesheet), we can create and design a simple loader such as a spinner or loading bars.

Step 1: Creating the Loader Design

Assuming that we have the following CSS script for the loader design. The result of the script below is a simple spinner loader in the whole page and displays the loader in the center.

  1. /** Loader Styles */
  2. #preloader {
  3. position: fixed;
  4. top: 0;
  5. left: 0;
  6. width: calc(100%);
  7. height: calc(100%);
  8. z-index: 999;
  9. background: #0000008f;
  10. display: flex;
  11. align-items: center;
  12. justify-content: center;
  13. }
  14. #preloader .lds-ring {
  15. display: inline-block;
  16. position: relative;
  17. width: 80px;
  18. height: 80px;
  19. }
  20. #preloader .lds-ring div {
  21. box-sizing: border-box;
  22. display: block;
  23. position: absolute;
  24. width: 64px;
  25. height: 64px;
  26. margin: 8px;
  27. border: 4px solid #fff;
  28. border-radius: 50%;
  29. animation: lds-ring 1.2s cubic-bezier(0.5, 0, 0.5, 1) infinite;
  30. border-color: #00b6ff transparent transparent transparent;
  31. }
  32. #preloader .lds-ring div:nth-child(1) {
  33. animation-delay: -0.45s;
  34. }
  35. #preloader .lds-ring div:nth-child(2) {
  36. animation-delay: -0.3s;
  37. }
  38. #preloader .lds-ring div:nth-child(3) {
  39. animation-delay: -0.15s;
  40. }
  41. @keyframes lds-ring {
  42. 0% {
  43. transform: rotate(0deg);
  44. }
  45. 100% {
  46. transform: rotate(360deg);
  47. }
  48. }
  49.  

Step 2: Creating the Loader Element using JavaScript

Next, using JavaScript we will create the loader element that will be used to append to the document body when the page loader is triggered.

  1. /**
  2. * Loader Element Creation
  3. */
  4. const loader = document.createElement('div')
  5. loader.setAttribute("id", "preloader")
  6. loader.innerHTML = `<div class="lds-ring"><div></div><div></div><div></div><div></div></div>`

Step 3: Creating the JS function for showing the Page Loader

Next, we will create a custom JS function that triggers to append the loader element to the document page.

  1. window.start_loader = function(){
  2. if(document.querySelector('#preloader') != null)
  3. document.querySelector('#preloader').remove()
  4.  
  5. document.body.appendChild(loader)
  6. }

Step 4: Create the JS function for Removes the Page Loader

Lastly, we'll create the custom JS function that checks if the page loader exists on the document and remove it.

  1. window.end_loader = function(){
  2. if(document.querySelector('#preloader') != null)
  3. document.querySelector('#preloader').remove()
  4. }

Copy and Paste both the CSS and Javascript in your sample web application on your end. Then, browse the application on your browser and open the browser developer tools on the sample application tab and navigate to the console panel of the developer tools window. Execute the start_loader() function in the console to show the page loader and the end_loader() function for hiding or removing the page loader.

Example

Here's a sample source code that demonstrates the reusable page loader in a web application.

Page Interface

index.html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <meta charset="UTF-8">
  4. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>JavaScript Reusable Loader</title>
  7. <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css" integrity="sha512-xh6O/CkQoPOWDdYTDqeRdPCVd1SpvCA9XXcUnZS2FmJNp1coAFzvtCN9BmamE+4aHK8yyUHUSCcJHgXloTyT2A==" crossorigin="anonymous" referrerpolicy="no-referrer" />
  8. <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
  9. <link rel="stylesheet" href="assets/styles.css">
  10. <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/js/all.min.js" integrity="sha512-naukR7I+Nk6gp7p5TMA4ycgfxaZBJ7MO5iC3Fp6ySQyKFHOGfpkSZkYVWV5R7u7cfAicxanwYQ5D1e17EfJcMA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
  11. <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script>
  12.  
  13. html, body{
  14. height: 100%;
  15. width: 100%;
  16. }
  17. body{
  18. display: flex;
  19. height: 100%;
  20. width: 100%;
  21. flex-direction: column;
  22. }
  23. body>nav, body>footer{
  24. flex-shrink: 1;
  25. }
  26. body>main{
  27. flex-shrink: 1;
  28. flex-grow: 1;
  29. overflow: auto;
  30. display: flex;
  31. flex-direction: column;
  32. width: 100%;
  33. align-items: center;
  34. justify-content: center;
  35. }
  36. pre{
  37. min-height:20vh
  38. }
  39. </style>
  40. </head>
  41. <body style="background:#eff3fc">
  42. <nav class="navbar navbar-expand-lg navbar-dark" style="background:#495C83">
  43. <div class="container">
  44. <a class="navbar-brand" href="./">JavaScript Reusable Loader</a>
  45. <div>
  46. <a href="https://sourcecodester.com" class="text-light fw-bolder h6 text-decoration-none" target="_blank">SourceCodester</a>
  47. </div>
  48. </div>
  49. </nav>
  50.  
  51. <main class="container-fluid">
  52. <div class="col-lg-6 col-md-8 col-sm-12 mx-auto">
  53. <h2 class="text-center">Creating a Reusable Loader using JavaScript and CSS</h2>
  54. <hr>
  55. <div class="card mt-3 rounded-0">
  56. <div class="card-body rounded-0">
  57. <div class="container-fluid">
  58. <div class="row justify-content-center">
  59. <div class="col-lg-4 col-lg-5 col-sm-6">
  60. <div class="mb-3">
  61. <button class="btn btn-primary rounded-pill w-100" type="button" id="show_loader_btn">Show Loader for 10sec</button>
  62. </div>
  63. <div class="mb-3">
  64. <a href="./redirect_page.html" class="btn btn-warning rounded-pill w-100">Redirect Page</a>
  65. </div>
  66. <div class="mb-3">
  67. <a href="#" onclick="location.reload()" class="btn btn-light border rounded-pill w-100">Reload Page</a>
  68. </div>
  69. </div>
  70. </div>
  71. </div>
  72. </div>
  73. </div>
  74. </div>
  75. </main>
  76. <footer class="container-fluid py-3" style="background:#495C83; color:#fff">
  77. <div class="container-fluid my-2">
  78. <div class="text-center">
  79. <b>JavaScript Reusable Loader &copy; 2023</b>
  80. </div>
  81. </div>
  82. </body>
  83. <script src="./assets/script.js"></script>
  84. </html>

redirect_page.html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <meta charset="UTF-8">
  4. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>JavaScript Reusable Loader</title>
  7. <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css" integrity="sha512-xh6O/CkQoPOWDdYTDqeRdPCVd1SpvCA9XXcUnZS2FmJNp1coAFzvtCN9BmamE+4aHK8yyUHUSCcJHgXloTyT2A==" crossorigin="anonymous" referrerpolicy="no-referrer" />
  8. <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
  9. <link rel="stylesheet" href="assets/styles.css">
  10. <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/js/all.min.js" integrity="sha512-naukR7I+Nk6gp7p5TMA4ycgfxaZBJ7MO5iC3Fp6ySQyKFHOGfpkSZkYVWV5R7u7cfAicxanwYQ5D1e17EfJcMA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
  11. <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script>
  12.  
  13. html, body{
  14. height: 100%;
  15. width: 100%;
  16. }
  17. body{
  18. display: flex;
  19. height: 100%;
  20. width: 100%;
  21. flex-direction: column;
  22. }
  23. body>nav, body>footer{
  24. flex-shrink: 1;
  25. }
  26. body>main{
  27. flex-shrink: 1;
  28. flex-grow: 1;
  29. overflow: auto;
  30. display: flex;
  31. flex-direction: column;
  32. width: 100%;
  33. align-items: center;
  34. justify-content: center;
  35. }
  36. pre{
  37. min-height:20vh
  38. }
  39. </style>
  40. </head>
  41. <body style="background:#eff3fc">
  42. <nav class="navbar navbar-expand-lg navbar-dark" style="background:#495C83">
  43. <div class="container">
  44. <a class="navbar-brand" href="./">JavaScript Reusable Loader</a>
  45. <div>
  46. <a href="https://sourcecodester.com" class="text-light fw-bolder h6 text-decoration-none" target="_blank">SourceCodester</a>
  47. </div>
  48. </div>
  49. </nav>
  50.  
  51. <main class="container-fluid">
  52. <div class="col-lg-6 col-md-8 col-sm-12 mx-auto">
  53. <h2 class="text-center">Creating a Reusable Loader using JavaScript and CSS</h2>
  54. <hr>
  55. <div class="card mt-3 rounded-0">
  56. <div class="card-body rounded-0">
  57. <div class="container-fluid">
  58. <div class="row justify-content-center">
  59. <div class="col-lg-4 col-lg-5 col-sm-6">
  60. <h3 class="text-center"><b>Sample Page</b></h3>
  61. <a href="./" class="btn btn-primary rounded-pill w-100">Back to Home</a>
  62. </div>
  63. </div>
  64. </div>
  65. </div>
  66. </div>
  67. </div>
  68. </main>
  69. <footer class="container-fluid py-3" style="background:#495C83; color:#fff">
  70. <div class="container-fluid my-2">
  71. <div class="text-center">
  72. <b>JavaScript Reusable Loader &copy; 2023</b>
  73. </div>
  74. </div>
  75. </body>
  76. <script src="./assets/script.js"></script>
  77. </html>

CSS

styles.css

  1. /** Loader Styles */
  2. #preloader {
  3. position: fixed;
  4. top: 0;
  5. left: 0;
  6. width: calc(100%);
  7. height: calc(100%);
  8. z-index: 999;
  9. background: #0000008f;
  10. display: flex;
  11. align-items: center;
  12. justify-content: center;
  13. }
  14. #preloader .lds-ring {
  15. display: inline-block;
  16. position: relative;
  17. width: 80px;
  18. height: 80px;
  19. }
  20. #preloader .lds-ring div {
  21. box-sizing: border-box;
  22. display: block;
  23. position: absolute;
  24. width: 64px;
  25. height: 64px;
  26. margin: 8px;
  27. border: 4px solid #fff;
  28. border-radius: 50%;
  29. animation: lds-ring 1.2s cubic-bezier(0.5, 0, 0.5, 1) infinite;
  30. border-color: #00b6ff transparent transparent transparent;
  31. }
  32. #preloader .lds-ring div:nth-child(1) {
  33. animation-delay: -0.45s;
  34. }
  35. #preloader .lds-ring div:nth-child(2) {
  36. animation-delay: -0.3s;
  37. }
  38. #preloader .lds-ring div:nth-child(3) {
  39. animation-delay: -0.15s;
  40. }
  41. @keyframes lds-ring {
  42. 0% {
  43. transform: rotate(0deg);
  44. }
  45. 100% {
  46. transform: rotate(360deg);
  47. }
  48. }
  49.  

JavaScript

script.js

  1. /**
  2. * Loader Element Creation
  3. */
  4. const loader = document.createElement('div')
  5. loader.setAttribute("id", "preloader")
  6. loader.innerHTML = `<div class="lds-ring"><div></div><div></div><div></div><div></div></div>`
  7.  
  8.  
  9. /** Show Loader to document */
  10. window.start_loader = function(){
  11. if(document.querySelector('#preloader') != null)
  12. document.querySelector('#preloader').remove()
  13.  
  14. document.body.appendChild(loader)
  15. }
  16.  
  17. /** Remove Loader From Document */
  18. window.end_loader = function(){
  19. if(document.querySelector('#preloader') != null)
  20. document.querySelector('#preloader').remove()
  21. }
  22.  
  23. /** Show Loader and remove it after 10 seconds on Show loader button is clicked */
  24. const show_loader_btn = document.getElementById('show_loader_btn')
  25. if(show_loader_btn !== null){
  26. show_loader_btn.addEventListener('click', function(e){
  27. e.preventDefault()
  28. start_loader();
  29. setTimeout(()=> {
  30. end_loader();
  31. },10000)
  32. })
  33. }
  34.  
  35.  
  36. /** Show Loader before unloading the document */
  37. window.addEventListener('beforeunload', async function(event){
  38. start_loader()
  39. event.returnValue = "Are you sure to leave this page?"
  40. })

Result Snapshot

Reusable Page Loader using CSS and JS

The source code above will result in a web application that contains the following features:

  • Display Page Loader on Page Reload
  • Display Page Loader when navigating to another Page
  • Display Page Loader and remove it after 10 seconds

DEMO VIDEO

I have also provided the source code zip file that I created for this tutorial and is free to download. The download button is located below this article/content.

That's the end of this tutorial. I hope this Creating a Reusable Page Loader using JavaScript Tutorial will help you with what you are looking for and that you'll find this useful for your current and future web application projects.

Explore more on this website for more Tutorials and Free Source Codes.

Happy Coding =)

Add new comment