Inline vs External Critical JS
You'll learn: When to embed critical JavaScript directly in HTML versus serving it as a cached external file.
Now that you understand critical JavaScript concepts, you face a practical decision: should you inline small, essential scripts directly in your HTML <head>, or keep them external and rely on browser caching?
The Core Trade-off
Inlining means embedding JavaScript directly between <script> tags in your HTML:
<script>
// Critical code that must run immediately
document.documentElement.className = 'js-enabled';
</script>
External files live separately and are referenced:
<script src="critical.js"></script>
When to Inline
Inline critical JS when:
- The script is tiny (< 1-2 KB) – the overhead of a separate HTTP request outweighs the bytes
- It's truly critical – must execute before first paint (like feature detection or theme switching)
- It changes frequently – caching won't help if the code updates often anyway
Think of it like carrying spare change in your pocket versus going to an ATM. For small amounts, the trip isn't worth it.
When to Keep External
Use external files when:
- The script is reusable across multiple pages – caching pays dividends
- It's larger (> 2 KB) – embedding bloats every HTML response
- It's stable – unchanged code benefits from long-term caching
The Compromise
For truly critical, tiny scripts needed instantly, inline them. For everything else, external + aggressive caching wins. You can also inline on first visit, then switch to cached external files for return visitors.
Key Takeaway: Inline critical JavaScript under ~1-2 KB that must run immediately; use external cached files for larger or reusable scripts to balance performance with cachability.