\n\n\n \n\n \n \n\n","image":"https://explain.codes/media/static/images/eightify-logo.svg","author":{"@type":"Person","name":"Nikita Barsukov","url":"https://explain.codes//author/nikita-barsukov"},"publisher":{"@type":"Organization","name":"Rational Expressions, Inc","logo":{"@type":"ImageObject","url":"https://explain.codes/landing/images/[email protected]"}},"datePublished":"2025-03-06T19:00:01.312Z","dateModified":"2025-03-06T19:00:03.167Z"}
Explain Codes LogoExplain Codes Logo

Should I write script in the body or the head of the html?

html
responsive-design
performance
defer
Nikita BarsukovbyNikita Barsukov·Mar 6, 2025
TLDR
**Embed `<script defer>` in `<head>`** for scripts that don’t require immediate DOM access. They'll load asynchronously with the page and execute after parsing, so performance stays sleek and smooth. **Place `<script>` before `</body>`** for scripts manipulating the DOM or reliant on its full structure. This keeps the scripts after the HTML, leaving the DOM primed for interaction. **Quick Example:** <head> <!-- Great for those non-DOM divas --> <script src="non-dom-script.js" defer></script> <!-- Load script but defer execution, it's like "Go have a coffee break, I'll call you later" --> </head> <body> <!-- All your lovely content --> <!-- Perfect spot for those DOM roughnecks --> <script src="dom-script.js"></script> <!-- "Now let's get down to business" --> </body>

When and Where? Contextualizing Script Placement

Let's get one thing straight—there's no absolute rule dictating where every script should go. Instead, it depends on specific script requirements, page performance, and user experience. Non-blocking scripts with async or defer attributes can be included in the <head>—they'll load simultaneously with the page but won't affect the loading of other content.

Scripts and Loading: A Balancing Act

The perennial challenge is this: how to ensure scripts don't compromise loading times while still doing what they need to. Generally, scripts placed at the bottom of the <body> boost load times as the HTML gets rendered first. However, for scripts critical for your page (like a font loader or a CSS-in-JS), remember the golden rule: up in the <head> with the defer attribute to make sure it's only executed after the HTML parsing, but before DOMContentLoaded.

Cleaner Code: Organizing Scripts

Keep those scripts neat and organized to ensure a clean, maintainable codebase. This often means grouping scripts in functions within the <head> or keeping them in distinct external files, steering clear of scattering inline code haphazardly throughout the markup.

Scripts and DOM: Timing it Right

To avoid those pesky DOM errors, use jQuery's document.ready() or the native DOMContentLoaded event for scripts that interact with the DOM, as they ensure your script only runs after the entire DOM is ready.

All about Placement: Strategies and Tools

Preserving Layout: Hidden Div Strategy

Scripts causing layout shifts mid-load? A hidden div approach might just do the trick! It's the page load equivalent of "keep it out of sight, out of mind" until the perfect moment.

External Scripts: Cache-Control

External scripts come with an added bonus—you can control their headers to optimize caching. This reduces load times on future visits, making users happier and your pages faster.

The Big Picture: Functionality vs Performance

Here's a big one—weigh each script's impact on functionality versus performance. Sure, inline scripts might offer quick functionality, but they can compromise performance. So, measure twice, cut once—balance them wisely in your pages.

Defer and Async: The Dynamic Duo

With async, scripts execute as soon as they're downloaded—not necessarily when the DOM is ready. Deferred scripts, on the other hand, hold their horses until the HTML is parsed, making them the perfect choice for scripts that are needed before the DOMContentLoaded event.

For jQuery Lovers: A Quick Tip

If jQuery is your jam, it's best to include the library in the <head>. This ensures it's ready and waiting for any subsequent scripts that need its help—like a good ol' toolkit!