Script Handling

Master the art of loading JavaScript efficiently without blocking your page rendering.

The Script Element

The <script> element is used to embed or reference executable code, typically JavaScript.

  • <script> : The tag used to define client-side scripts.
  • Inline scripts : Code written directly between the <script> tags within your HTML file.
  • External scripts : Using the 'src' attribute to link to a separate .js file, which is better for organization and caching.
  • <noscript> : Defines an alternate content for users that have disabled scripts in their browser or have a browser that doesn't support scripts.

Inline Script

JavaScript written directly inside <script> tags in your HTML.

Loading Strategies

How you load a script determines whether your user sees a blank screen or a fully rendered page while the code downloads.

  • Normal Execution : The HTML parser stops, downloads the script, executes it, and then continues parsing.
  • async : The script is downloaded asynchronously while HTML parsing continues, but it pauses parsing to execute as soon as it's ready.
  • defer : The script is downloaded asynchronously, and execution only happens after the HTML document has been fully parsed.
  • type='module' : Treats the script as a JavaScript module, enabling features like 'import' and 'export', and defers execution by default.

Script Placement

Place <script> after the element it targets, or use the defer attribute on external scripts.

Modern Best Practices

In modern web development, performance is key. Choosing the right loading method can significantly improve your core web vitals.

  • Use 'defer' for scripts that need to manipulate the DOM (the elements on the page).
  • Use 'async' for independent scripts like analytics or ads that don't care when they run.
  • Place standard scripts at the bottom of the <body> if you aren't using defer/async to prevent render-blocking.
  • Always provide a <noscript> message if your site's core functionality depends on JavaScript.

Knowledge Check

1. Which attribute ensures a script is executed only after the entire HTML document has been parsed?

2. What happens to the HTML parser when a standard <script> (without async or defer) is encountered?

3. Which tag provides fallback content for users who have disabled JavaScript in their browser?

4. When using 'type="module"', which behavior is enabled by default?

5. Which attribute is best for independent third-party scripts (like ads or analytics) that don't depend on other scripts?

6. What is the difference between inline and external scripts?