DEV Community

Syed Ammar
Syed Ammar

Posted on

Better way to add external script in html page and why?

When deciding whether to add an external script in the <head> tag or before the closing </body> tag, the choice depends on how the script affects your page and performance considerations.

1. Adding the Script in the <head>

  • Best for: Critical scripts that need to load early.
  • Examples:
    • Scripts necessary for the structure or functionality of the page, like frameworks or libraries (e.g., AngularJS, React).
    • Analytics tools that should capture data right as the page begins loading.
  • Drawback: If not handled carefully, scripts in the <head> can block rendering, leading to slower page load times and a poor user experience.
  • Solution: Use the async or defer attribute:
    • async: Loads the script asynchronously without blocking the page but executes it as soon as it's downloaded.
    • defer: Loads the script in order and delays execution until the HTML is fully parsed, which prevents blocking.
   <head>
       <script src="important-script.js" defer></script>
   </head>
Enter fullscreen mode Exit fullscreen mode

2. Adding the Script Before the Closing </body>

  • Best for: Non-critical or user-interaction scripts.
  • Examples:
    • Scripts for user interactions, animations, or enhancements that don't affect the initial rendering.
    • Third-party integrations like chatbots or social widgets.
  • Benefits:
    • Ensures the page's content is loaded and rendered first, providing a faster "perceived load time" for users.
    • Non-blocking, as the script loads after the page content.
   <body>
       <!-- Content -->
       <script src="enhancement-script.js"></script>
   </body>
Enter fullscreen mode Exit fullscreen mode

Key Differences

Criteria In <head> Before </body>
Blocking Potential Higher (unless defer) Lower
User Experience Impact Critical scripts, early load Non-critical scripts, delayed load
Performance May slow down rendering Ensures content loads first

Conclusion:

  • Use the <head> for essential scripts (with defer or async).
  • Use before </body> for scripts that enhance interactivity or are less critical for initial page rendering.

This approach balances performance with functionality, ensuring a smooth user experience.

Top comments (0)