Overview
TheloadScript function dynamically loads external JavaScript files into the HTML document. It provides control over loading strategies (defer/async), prevents duplicate script loading, and supports callbacks for post-load execution.
Location
Function Signature
Parameters
The URL of the script to load. Can be:
- Full URL with protocol:
https://example.com/script.js - Protocol-relative URL:
//example.com/script.js - Domain-only URL:
example.com/script.js(auto-prepended withhttps://)
The loading strategy for the script:
"defer"- Script executes after HTML parsing completes"async"- Script executes as soon as it’s available
Optional callback function to execute when the script finishes loading.
If
true, executes the callback even when the script is already loaded (skipped duplicate).Returns
Type:void
This function does not return any value.
Implementation Details
URL Normalization
The function automatically normalizes URLs to use HTTPS:Duplicate Prevention
Before loading, the function checks if a script with the same source already exists:Script Element Creation
The function creates a script element with appropriate attributes:Usage Examples
Basic Script Loading (Deferred)
Async Loading with Callback
Protocol-Relative URL
Real-World Example (from main.js)
Loading balance-text for Safari browsers:Using in Alpine.data Components
The loadScript function is available in the xDOM component:Loading Strategies
Defer vs Async
Callback Behavior
Standard Callback
Callback executes only when the script is freshly loaded:Forced Callback
Callback executes even if script was already loaded:Best Practices
- Use
deferfor scripts that depend on DOM content - Use
asyncfor independent scripts (analytics, ads) - Always provide callbacks for scripts that require initialization
- Use protocol-relative URLs (
//) to match the page protocol
Security
All dynamically loaded scripts include thecrossOrigin="anonymous" attribute for CORS compliance.
Related
- main.js - Uses loadScript for conditional script loading
- Alpine.data (xDOM) - Exposes loadScript in Alpine components