{{ document.script }} – Add JavaScript Script

The document.script function allows you to add JavaScript to your page, either by including external JS files or embedding inline scripts.

Description

This tag provides a flexible way to inject JavaScript into your document’s <head> section. It can handle both external JavaScript file references and direct JavaScript code.

Syntax:

{# Include external JavaScript file #}
{{ document.script(fileUrl) }}

{# Add inline JavaScript #}
{{ document.script(jsContent) }}

Parameters:

  • fileUrl (string): URL or path to the JavaScript file
  • jsContent (string): Direct JavaScript code to be embedded

Behavior

  • When provided with a URL or file path, creates a <script> tag with the src attribute
  • When provided with JavaScript code, creates a <script> tag containing the provided code
  • Automatically injects the resulting tags into the document’s <head> section

Examples

Including External JavaScript File

{# Add jQuery #}
{{ document.script("https://code.jquery.com/jquery-3.6.0.min.js") }}

{# Add local JavaScript file #}
{{ document.script("/templates/custom/scripts.js") }}

Adding Inline JavaScript

{# Add custom JavaScript directly #}

{{ document.script("
function initializeWidget() {
   const element = document.querySelector('.widget');
   if (element){
     element.addEventListener('click', function() {
         console.log('Widget clicked');
     });
   } 
} 

document.addEventListener('DOMContentLoaded', initializeWidget); 

") }}

Integration

Works seamlessly in both WordPress and Joomla environments, handling proper integration with the respective CMS’s asset management systems.

Best Practices

  1. Use external JavaScript files for larger scripts to benefit from browser caching
  2. Reserve inline scripts for small, page-specific functionality
  3. Consider load order when adding multiple script declarations
  4. Use relative paths for local files when possible
  5. Ensure file paths are correct relative to your site’s root directory
  6. Place scripts that depend on other libraries after their dependencies

Important Notes

  • The extension automatically handles proper HTML encoding
  • Scripts are added in the order they are declared
  • Duplicate script inclusions are typically handled by the browser
  • Works in front-end context only
  • Consider using defer or async attributes for external scripts when appropriate (currently managed by the browser/CMS defaults)


What are your feelings

Leave a Reply

Updated on January 20, 2025