Skip to content
Advertisement

How to call a JavaScript function when the external JavaScript file is referenced at the end of the HTML body?

I know that when you want to invoke a JavaScript function inside a HTML body section you can do it by putting <script> someFunction(); </script> inside your body tag, here is an example, I have HTML like this:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>

<head>
<script type="text/javascript"
    src="/Script.js"></script>
</head>

<body>
    <script>
        showAlert();
    </script>
</body>

</html>

And the javascript file like this:

function showAlert(){
    alert("This is an alert!");
}

This works fine but if I put the JavaScript file reference at the end of the body like this:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>

<head>
</head>

<body>
    <script>
        showAlert();
    </script>
    <script type="text/javascript"
        src="/Script.js"></script>
</body>

</html>

the function showAlert() is no longer being invoked. Can you please answer these 2 questions:

  1. Why is showAlert() not invoked in the second scenario?
  2. How (if possible) to invoke a function from a JavaScript file when it is referenced in the end of the body?

The reason why I’m asking is because I know that it is a good practice to refer your JavaScript files in the end of the body instead of the head, so that the page will be rendered first before loading all the JavaScript code.

Advertisement

Answer

Assuming you want to run showAlert() immediately when the page has loaded, try adding an onload() event handler to call showAlert rather than just calling it as the script loads. This can be done a few ways:

<body onload="showAlert();">

or define the window onload event programatically where your current function all is made in the html

window.onload = new function() {showAlert();}

or (and I think this is the preferred way because it won’t cancel out other event handlers bound to the onload event)

window.addEventListener("load", showAlert);
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement