Reputation: 2453
I have read about several ways to embed Javascript in HTML document. First, in head section:
<head>
...
<script src="abc.js"></script>
</head>
Second, in the end of document's body:
<body>
<!-- content -->
<script src="abc.js"></script>
</body>
First way is more esthetic, but second version assures that all the items in DOM are loaded. I use HTML5 (but probably it doesn't matter)
Which way is better and why?
Upvotes: 0
Views: 130
Reputation: 6346
if it is just a library of functions which aren't suppose to run when the page loads, you can safely put it in the head. Otherwise you need to wrap the code in abc.js
with window.onload
or $(document).ready();
and then embed it in the head
Upvotes: 2
Reputation: 4163
A lot depends on when you need script to execute if you need the page to be fully loaded or not. You can possibly put it in the head then execute a function with the onload
event.
Upvotes: 1
Reputation: 4504
It depends on when you need the functionality in the script. Before page load or else. If it doesn't matter the second one in your example is better and more seciure since it allows the page content to load. An error in the script may prevent for this to happen in before body case.
Upvotes: 2