0

I'm using an event which is called after the complete site is loaded. So I use onload() for that.

Is there any way to call my function before or during the site is loaded?

I would be very grateful! Thank You!

Jan
  • 277
  • 1
  • 6
  • 16
  • 1
    Just put it in a script tag. – Dave Newton Feb 28 '17 at 15:05
  • And how do I call my function? – Jan Feb 28 '17 at 15:06
  • 1
    Put a script tag with function call in head. But it depends on the function. There is also DOMContentLoaded which happens before onload. – dfsq Feb 28 '17 at 15:06
  • If you want your code to be loaded before the HTML of your webpage is loaded, place the – noa-dev Feb 28 '17 at 15:06
  • I believe you are mistaking document ready and window load. You're probably interested in document ready, simplest way to do that is to put your javascript as the last thing before the `` close. – Dominic Feb 28 '17 at 15:07
  • possible duplicate of http://stackoverflow.com/questions/2920129/can-i-run-javascript-before-the-whole-page-is-loaded – shrinathM Feb 28 '17 at 15:08

3 Answers3

1
<html>
  <head>
    <title>My title</title>
    <script>
      var x = 2;
      function timesTwo(num){
        return num * 2;
      }
      console.log(timesTwo(x));
    </script>
  </head>
  <body>
    <h1>Hello World</h1>
  </body>
</html>

That way your JavaScript code is being interpreted and executed before the websites Body is being rendered. Keep in mind, that if you use that approach and are executing some JS that takes up some time, the websites display time will be delayed by same amount.

noa-dev
  • 3,561
  • 9
  • 34
  • 72
0

If you want to call something as early as possible, put it in a script tag at the beginning of the <head> element. However, you can't guarantee any libraries are loaded or any of the page has been loaded yet. If you want to do something as soon as possible, and are using jquery, use $(function() { yourFunctionHere() }). If you aren't using jquery, use the DOMContentLoaded event

Jim Deville
  • 10,632
  • 1
  • 37
  • 47
0

You may listen on the 'readystate' event to do something before the 'DOMContent' event. And do not forget to put the snippet in head tag.

<html>
<head>
<script>
document.addEventListener('DOMContentLoaded', function () {
    console.log('DOM content loaded');
};
document.addEventListener('readystatechange', function () {
    console.log('[Ready state is]', document.readystate);
    if (document.readystate != 'complete') {
        console.log('You can do something here');
    }
};
</script>
<body>
</body>
</html>

The output can be:

[Ready state is] interactive
You can do something here
DOM content loaded
[Ready state is] complete

Hope it helps.

Zmen Hu
  • 795
  • 3
  • 12