kay am see
kay am see

Reputation: 988

How to delay the onLoad event which gets fired on the browser?

I am trying to delay the onLoad event that gets fired. Is there a way to delay this event strictly using javascript on the client side ?

Upvotes: 8

Views: 24342

Answers (3)

jcaruso
jcaruso

Reputation: 1020

I ended up on this page hoping for a quick answer. Looks like its been a while without one so I thought I'd instead do the work to solve it.

My goal here was for testing slow loading pages, not because I want to slow down an event load in production.

You can accomplish a delay in page load by requesting a slow resource. My trick to achieve this was to serve a PHP file with a 10 second sleep in it. This delays page load, but allows other events to fire (like DOMContentLoaded)

<?php
    header('Content-Type: application/javascript');
    sleep(10);
    echo "var x = 1;";

Then just request it at the bottom of my test page

<script src="http://localhost:8000/delay.php" async></script>

Here is a codepen with the full example. You will need to serve the php file youself somewhere though.

https://codepen.io/jgcaruso/pen/vYwpwRB

Upvotes: 0

Mic
Mic

Reputation: 25164

If you put a script tag at the end of the body like:

<body>

  ...

  <script>
    setTimeout(function(){
      //deferred onload
    }, 2000);
  </script>
</body>

The function will be executed after 2 sec in this case

As said in my comment below: you shouldn't rely on a delay. But use a callback on a certain event. If impossible, may be a better bad solution, is to use setInterval with a function that check every X msec if the thing you are waiting for is present, and fire.

Upvotes: 9

Ryre
Ryre

Reputation: 6181

There's no reason to delay the onload event. Maybe you want to use window.load instead?

$(window).load(function(){
    //your code here
});

Upvotes: -10

Related Questions