How to Run JavaScript Before the Whole Page Is Loaded

Can I run javascript before the whole page is loaded?

Not only can you, but you have to make a special effort not to if you don't want to. :-)

When the browser encounters a classic script tag when parsing the HTML, it stops parsing and hands over to the JavaScript interpreter, which runs the script. The parser doesn't continue until the script execution is complete (because the script might do document.write calls to output markup that the parser should handle).

That's the default behavior, but you have a few options for delaying script execution:

  1. Use JavaScript modules. A type="module" script is deferred until the HTML has been fully parsed and the initial DOM created. This isn't the primary reason to use modules, but it's one of the reasons:

    <script type="module" src="./my-code.js"></script>
    <!-- Or -->
    <script type="module">
    // Your code here
    </script>

    The code will be fetched (if it's separate) and parsed in parallel with the HTML parsing, but won't be run until the HTML parsing is done. (If your module code is inline rather than in its own file, it is also deferred until HTML parsing is complete.)

    This wasn't available when I first wrote this answer in 2010, but here in 2020, all major modern browsers support modules natively, and if you need to support older browsers, you can use bundlers like Webpack and Rollup.js.

  2. Use the defer attribute on a classic script tag:

    <script defer src="./my-code.js"></script>

    As with the module, the code in my-code.js will be fetched and parsed in parallel with the HTML parsing, but won't be run until the HTML parsing is done. But, defer doesn't work with inline script content, only with external files referenced via src.

  3. I don't think it's what you want, but you can use the async attribute to tell the browser to fetch the JavaScript code in parallel with the HTML parsing, but then run it as soon as possible, even if the HTML parsing isn't complete. You can put it on a type="module" tag, or use it instead of defer on a classic script tag.

  4. Put the script tag at the end of the document, just prior to the closing </body> tag:

    <!doctype html>
    <html>
    <!-- ... -->
    <body>
    <!-- The document's HTML goes here -->
    <script type="module" src="./my-code.js"></script><!-- Or inline script -->
    </body>
    </html>

    That way, even though the code is run as soon as its encountered, all of the elements defined by the HTML above it exist and are ready to be used.

    It used to be that this caused an additional delay on some browsers because they wouldn't start fetching the code until the script tag was encountered, but modern browsers scan ahead and start prefetching. Still, this is very much the third choice at this point, both modules and defer are better options.

The spec has a useful diagram showing a raw script tag, defer, async, type="module", and type="module" async and the timing of when the JavaScript code is fetched and run:

Sample Image

Here's an example of the default behavior, a raw script tag:

.found {    color: green;}
<p>Paragraph 1</p><script>    if (typeof NodeList !== "undefined" && !NodeList.prototype.forEach) {        NodeList.prototype.forEach = Array.prototype.forEach;    }    document.querySelectorAll("p").forEach(p => {        p.classList.add("found");    });</script><p>Paragraph 2</p>

How to run JavaScript code before page load?

You can use window.onpaint for such purpose like :

<script type="text/javascript">
function preloadFunc()
{
alert("PreLoad");
}
window.onpaint = preloadFunc();
</script>

I hope it helps you....

How to execute a function when page has fully loaded?

That's called load. It came waaaaay before DOM ready was around, and DOM ready was actually created for the exact reason that load waited on images.

window.addEventListener('load', function () {
alert("It's loaded!")
})

How to make JavaScript execute after page load?

These solutions will work:

As mentioned in comments use defer:

<script src="deferMe.js" defer></script>

or

<body onload="script();">

or

document.onload = function ...

or even

window.onload = function ...

Note that the last option is a better way to go since it is unobstrusive and is considered more standard.

How to run a function when the page is loaded?

window.onload = codeAddress; should work - here's a demo, and the full code:

<!DOCTYPE html><html>    <head>        <title>Test</title>        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />        <script type="text/javascript">        function codeAddress() {            alert('ok');        }        window.onload = codeAddress;        </script>    </head>    <body>        </body></html>

Call javascript function before page loads

No, can't (or shouldn't) force the body onload event to fire, but you can add a script tag immediately after the element in question.

<a id="beginner">Beginner Level</a>
<div id="beginner-sub" class="well">
<!-- append content here -->
</div>
<script>load();</script>

Do note though, that any other functions the load() depends on must have been loaded or else it will fail



Related Topics



Leave a reply



Submit