JavaScript: Show Loading Screen until certain assets are fully loaded

Just a quick overview.
I currently have a loading screen that appears before the website finishes loading for a specified time. What I'm looking to achieve is a method to check if certain elements are loaded and then remove the loading screen, rather than relying on a fixed duration.

In my example, I want to determine when images have been completely loaded and displayed in order to end the loading screen. Additionally, I would like to learn how to apply this technique to any other element, like a random div or paragraph if feasible.

fiddle: https://jsfiddle.net/jzhang172/Lyv17L0n/1/

$(document).ready(function() {
 
    setTimeout(function(){
        $('body').addClass('loaded');
        $('h1').css('color','#222222');
    }, 500);
 
});
.loaded{
transition:1s;
}


.content{
  background:gray;
  height:500px;
  width:100%;
  
}

#loader-wrapper{
  position:fixed;
  background:black;
  top:0;
  bottom:0;
  left:0;
  right:0;
  transition:1s;
  
}
.loaded #loader-wrapper{
  opacity:0;
}
.loader-section{
  position:fixed;
  top:0;
  bottom:0;
  background:red;
  z-index:5;
  width:51%;
  transition:1s;
    opacity:1;
  
}
.section-left{
  left:0;
}
.section-right{
  right:0;
}


.loaded .loader-section.section-left{
  opacity:0;
  transform:translateX(-100%);
  transition:1s;
}
.loaded .loader-section.section-right{
    opacity:0;
  transform:translateX(100%);
  transition:1s;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
      <div id="loader-wrapper">
<div id="loader"></div>
<div class="loader-section section-left"></div>
<div class="loader-section section-right"></div>
    </div>
  <div class="content">
    <img src="https://upload.wikimedia.org/wikipedia/en/2/22/Kirby_Wii.png">
     <img src="https://upload.wikimedia.org/wikipedia/en/2/22/Kirby_Wii.png">
      <img src="https://upload.wikimedia.org/wikipedia/en/2/22/Kirby_Wii.png">
       <img src="https://upload.wikimedia.org/wikipedia/en/2/22/Kirby_Wii.png">
       
  </div>
  
</body>

Answer №1

One solution is to utilize the following plugin:

$('body').waitForImages(

function() {
    ...CODE FOR EACH LOAD...
}, function(loaded, total) {
    if(loaded / total == 1){
       ...CODE FOR FULLY LOAD...
    }
});

This plugin can be customized to target divs and text elements as well. However, it is particularly effective in optimizing image loading times.

You can witness this plugin in action here:

http://jsfiddle.net/2sc0rtzL/

Answer №2

I attempted calling your code within the window.load function, hopefully it will be successful for you.

The window.load function verifies that all resources on the page are loaded before executing.

https://jsfiddle.net/abc123/

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Correctly align the div on the screen as the viewport is scrolled

I am currently working on a parallax website where the sliders are designed to slide from the left and align within the viewport as the user scrolls. However, I have encountered an issue where multiple scroll actions are required for the slide to align pro ...

Tips for sending an unchecked checkbox to a post

I am facing an issue where only the checked checkboxes are being sent in $_POST. I want the checked checkboxes to have a value of 'true' and the unchecked ones to have a value of 'false' in $_POST. Is there a way to achieve this or does ...

An unusual contrast between .css and .animate when using percentage positioning in jQuery

I've encountered a situation where my code behaves as expected, but I noticed that the first animation has a duration of 0. $(".myClass").animate({'top': '-=100%'}, 0).animate({top: '+=100%'}, 500); In essence, I'm ...

Is it a bad idea to set directive scope to false, considering the limitations on broadcasting in an isolated scope?

There is a unique situation I am trying to tackle where I need to use $broadcast within a directive's linking function that has an isolated scope. Unfortunately, broadcasting from inside an isolated scope becomes challenging as the directive scope doe ...

Exploring ways to find a particular value within an array of objects

Struggling to make my code render the data upon searching for a specific value. I attempted using a for loop, but I keep encountering an 'unexpected token' error. Is there a more effective way to accomplish this task? While this may seem like a s ...

NodeJS encountered a SyntaxError while trying to export the 'routes' object as

const paths = (app) => { app.route('/contact') .get((req, res, next) => { // middleware console.log(`Request from: ${req.originalUrl}`) console.log(`Request type: ${req.method}`) next(); }, (req, res, next) = ...

Interpret a JavaScript array response

Currently, I am working on an API request where I receive an HTTP response that contains an array with a single JSON object. However, when attempting to parse or stringify it using the following code: var response = http.response; try{ var json = J ...

The Raycast function seems to be failing to detect the GlTF file in Three.js

After creating a binary gltf file in Blender and animating it with Mixamo, I am encountering an issue where it is not being detected on raycast. Despite trying numerous tutorials and solutions, I have been unable to resolve the issue. const loader = new GL ...

What is the best way to ensure that the radius of the circle adjusts according to the canvas element in

I've successfully drawn a circle on a canvas element, but now I need to make it responsive. How can I achieve this? I want the radius of the circle to change by a certain amount when the browser width or height changes. How do I calculate this changi ...

Exploring the behavior of Object.assign in for loops and forEach loops

I've come across an interesting anomaly with Object.assign in the following scenario. function sampleFunction(index, myList) { myList.forEach((element, i) => { if (i === index) { console.log(Object.assign({}, {"newKey": " ...

What is the best way to swap out the if else statement with a Ternary operator within a JavaScript function?

Is there a way to replace the if else statement in the function using a Ternary operator in JavaScript? private getProductName(productType: string): string { let productName = 'Product not found'; this.deal.packages.find(p => p.isSele ...

The panel's placement shifts when the browser window is expanded

Currently, the issue I am encountering involves an ASP.NET website with a header, sidebar, and additional right sidebar. When I resize the browser window, the left sidebar overlaps the content page, resulting in mixed-up controls. Please refer to the image ...

Modify the current link's <li> class

I am facing an issue with the code below which is supposed to change the class of li based on whether the browser URL matches the href attribute within that li. The current problem I am encountering is that the code changes the class for all li elements, ...

Using ASP.NET MVC 6 Web API along with Angular, a resource can be posted as an object property in the

I am facing a challenge in sending a complex object from Angular to my web API. Here is how the object looks: { Name: "test", Tax: 23, Addresses: [ { country: "ro", city: "bucharest" }, { country: "fr", ...

Ways to make text within a container smoothly slide down

Hello, I have a question about jQuery as I am relatively new to it. I am currently working on creating a team members section where clicking on a team member will slide down information about that person underneath. I have managed to set up the parent co ...

Fields that change dynamically on websites

I am currently working on enhancing a User profile page by adding 2 additional field types, but I am encountering difficulties in implementing them. Essentially, both field types are dynamic in nature. One involves a selection from a list, with the option ...

Navigating to User's Specific Info Page using Node.js

Would love some input on my current issue. I have a table featuring a list of users, and my goal is to display user information in detail whenever a user (which corresponds to a row in the table) is clicked. The process involves identifying which user was ...

Promise-based React Redux Login: An error occurred during login process

I'm currently working on my first React+Redux application and I'm still in the scaffolding phase. As a newcomer to React, I've encountered an issue with my simple login app. The AuthAction returns a Promise from the login(username, password) ...

Retrieving data from Firebase in an asynchronous manner

I am currently working on a business management web application using React with Firebase for the backend. I have also implemented a local API to simplify some of the Firebase functions. One of the methods I created is designed to retrieve data from a spec ...

Prevent URL changes for specific pages in React Router

Is there a way to maintain certain page URLs without changing them? I am aware that by using "MemoryRouter", I can navigate through different pages using history.push without altering the URL. However, I would like to change the URL for specific pages. Is ...