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!
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!
<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.
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
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.