-1

Please could someone help me with this set of code

How can I set an event.listener to initiate code when the page has finished loading. At the moment I have used a setTimeOut but on slow connections the time out for the loader to disappear is too soon, I would like to do it without having to increase the interval time, to initiate the code only once the page and its content has finished loading. I would greatly appreciate your help. please see my code below

$('body').append('<div id="loadingDiv"><div class="loader"><img src="./images/loader/image.gif" alt="loadingImage"></div></div>');

  let clearLoader = () => {
    $("#loadingDiv").fadeOut(500, function () {
      $("#loadingDiv").remove();
    });
  }
  
  setTimeout(clearLoader, 2000);
  • Listen for a [load event](https://developer.mozilla.org/en-US/docs/Web/API/Window/load_event). – ray Sep 03 '20 at 16:25

1 Answers1

0

You can use onload event for the window object like the vanilla javascript snippet below:

window.onload = function (){
  console.log('Window finished loading.');
}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>After loading window</title>
</head>
<body>
  
</body>
</html>

OR

jQuery way:

$(window).load(function(){
  console.log('Window finished loading.');
});
  • I tried that code, the loader still fades out after my designated time interval, and not after the page has finished loading. – Gary Tarantino Sep 03 '20 at 17:18
  • Ok, then you may check out this answer by @Viscocent ; https://stackoverflow.com/a/23907579/10636406 –  Sep 03 '20 at 17:36