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 filejsContent
(string): Direct JavaScript code to be embedded
Behavior
- When provided with a URL or file path, creates a
<script>
tag with thesrc
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
- Use external JavaScript files for larger scripts to benefit from browser caching
- Reserve inline scripts for small, page-specific functionality
- Consider load order when adding multiple script declarations
- Use relative paths for local files when possible
- Ensure file paths are correct relative to your site’s root directory
- 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
orasync
attributes for external scripts when appropriate (currently managed by the browser/CMS defaults)
Leave a Reply
You must be logged in to post a comment.