简体   繁体   中英

Where exactly should I attach script in HTML?

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?

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM