-1

So, one can use:

<body onload="myFunction()">

To run a function after the page has loaded, but I want the opposite to happen.

Something like:

<html>
    <script> 
        function loadBodyNow(){
            ....
        }
        loadBodyNow() 
    </script>

    <body>
        Hello world!
    </body>
</html>
Sébastien
  • 11,860
  • 11
  • 58
  • 78
Kanerva Peter
  • 237
  • 5
  • 13

2 Answers2

0

Don't put the script tag after the body. Put all your script tags in your head element and do this:

<script>
  window.addEventListener('load', function() {
    // body is loaded! execute code here
  })
</script>
0

Loading of the document is the browser's job, it does not require JavaScript

Unless JavaScript is blocking the browser with an alert() for example, the browser will load the HTML as fast as it can when the source is received.

<script>
var blocking = function() {
  alert('blocking')
}
</script>
<p>First paragraph</p>
<script>
  blocking()
</script>
<p>Second paragraph</p>

The above example might not even work in all browsers. In Firefox you will see that the first paragraph is rendered, then you get the alert, and only one you dismiss the alert does the rendering continue to the second paragraph.

You can stop the laoding of the page with

window.stop();

But you will not be able to resume loading...

So if you want the body to load only when you execute a JavaScript function, you will have to leave you <body> empty and generate its content entirely in JavaScript.

var loadBodyNow = function() {
  var elm = document.createElement('p');
  elm.innerHTML = '<strong>Hello World!</strong>';
  document.body.appendChild(elm)
}

setTimeout(loadBodyNow, 2000);
<body>
</body>

Alterrnatively, you could use an iframe to load remote content when you want, by inserting it with JavaScript.

Sébastien
  • 11,860
  • 11
  • 58
  • 78