PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, July 18, 2022

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

 July 18, 2022     document-body, dom, html, javascript     No comments   

Issue

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?


Solution

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.



Answered By - statosdotcom
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing