Bubba Yakoza
Bubba Yakoza

Reputation: 799

How to load external javascript file first before using it in BODY onload event?

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

<body onload="someFunctionInExternalJS();">
</body>

How do I ensure that externaljs.js is loaded first so that someFunctionInExternalJS() is executed as a result? Thanks!

Upvotes: 5

Views: 21683

Answers (3)

Paulo
Paulo

Reputation: 170

using jquery,

$(document).ready(function() {
    //anything in here will only be called/work when the document is ready.

 //call your function in here, instead of bodyonload
});

Upvotes: 2

Blake A. Nichols
Blake A. Nichols

Reputation: 870

The external javascript file will load and execute before continuing along and building the DOM, unless it is async (http://www.w3schools.com/tags/att_script_async.asp).

Any external file that the DOM requires to build (javascript, css primarily) will load as it is being parsed. This is why you will sometimes see javascript at the bottom of the body tag instead of the head.

Upvotes: 2

Lo&#239;c Poullain
Lo&#239;c Poullain

Reputation: 82

I tested this code and it works fine :

<!doctype html>
<html>
 <head>
 <script src="my_script.js"></script>
 </head>
<body onload="my_function()">

</body>
</html>

with this in my_script.js :

function my_function () {
    alert("Hello world!");
    }

Another solution is to write this in my_script.js :

function my_function () {
    alert("Hello world!");
    }

document.onload = my_function();

Upvotes: 2

Related Questions