5
<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!

8
  • "How do I ensure?" Test it! Commented Aug 15, 2014 at 18:20
  • Tested ... not working Commented Aug 15, 2014 at 18:21
  • would you like to show the someFunctionInExternalJS(); function? Commented Aug 15, 2014 at 18:21
  • That's just an example it could be any function in externaljs.js file Commented Aug 15, 2014 at 18:23
  • 1
    call your JS function inside window.onload event instead Commented Aug 15, 2014 at 18:31

3 Answers 3

2

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();
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

2

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
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.