Lone Learner
Lone Learner

Reputation: 20698

How to run JavaScript code as soon <body> element is defined?

Here is my code:

<!DOCTYPE html>
<html>
<head>
  <title>Foo</title>
</head>
<body>

  <script>
    console.log('test')
  </script>

  <p>
    Foo
  </p>

</body>
</html>

I want to move the JavaScript in this code from <body> into <head>. Here is my incorrect attempt:

<!DOCTYPE html>
<html>
<head>
  <title>Foo</title>
  <script>
  window.onload = function () {
    console.log('test')
  }
  </script>
</head>
<body>

  <p>
    Foo
  </p>

</body>
</html>

This of course does not do what I want. It runs the JavaScript only after the whole page has loaded. But I want the JavaScript to run as soon as <body> is defined. Can this be done in JavaScript?

Upvotes: 1

Views: 2951

Answers (1)

Insert your log command into a defined Javascript function at the <head> part of your Html and call this function soon after the opening of <body>.

Your final code will look this way:

<!DOCTYPE html>
<html>
<head>

<script>
function myFunction(){
  console.log('test');
}
</script>

<title>Foo</title>
</head>

<body>

<script>
  myFunction();
</script>

<p>
Foo
</p>

</body>
</html>

It's worth to mention that the onload event-property do exists in another html tags too, and only on those cases it is executed right after it's definition, which means: immediately.

With <body> tag happens something singular: the onload only runs after two conditions:

1) the express definition of </body>;

2) the finishing of the loading of all accessory and maybe external routines and resources, which means: the loading of all html, css, jpg, gif, svg etc.

So, the onload do what it promises: runs when and only after page 100% loaded.

Upvotes: 3

Related Questions