Dynamically load JS inside JS
Categories:
Dynamically Loading JavaScript Files in Your Web Applications

Learn various techniques to dynamically load JavaScript files after the initial page load, improving performance and modularity in your web projects.
Dynamically loading JavaScript files is a powerful technique that allows you to fetch and execute scripts on demand, rather than including them all in the initial page load. This approach offers several benefits, including improved page load performance, better resource management, and the ability to create more modular and flexible applications. This article explores different methods for achieving dynamic script loading, from native JavaScript solutions to leveraging libraries like jQuery.
Why Dynamic Script Loading?
In modern web development, optimizing performance is crucial. Loading all JavaScript files upfront, especially for large applications, can lead to slower initial page loads and a poor user experience. Dynamic script loading addresses this by:
- Reducing Initial Load Time: Only essential scripts are loaded initially, deferring less critical ones until they are actually needed.
- Resource Management: Scripts can be loaded based on user interaction, route changes, or specific conditions, preventing unnecessary resource consumption.
- Modularity: It promotes a more modular architecture, allowing you to break down your application into smaller, manageable chunks that can be loaded independently.
- Feature Flags & A/B Testing: Easily load different script versions or features based on user segments or experimental conditions.
flowchart TD A[User Navigates to Page] --> B{Initial HTML/CSS/JS Loaded} B --> C{Is Feature X Needed?} C -- No --> D[Continue Interaction] C -- Yes --> E[Dynamically Load script-x.js] E --> F[Execute script-x.js] F --> D
Flowchart illustrating the dynamic loading process based on a feature requirement.
Native JavaScript Methods
The most fundamental way to dynamically load JavaScript is by programmatically creating a <script>
element and appending it to the DOM. This method gives you fine-grained control over the script's attributes and its loading behavior.
function loadScript(url, callback) {
var script = document.createElement('script');
script.type = 'text/javascript';
if (script.readyState) { //IE
script.onreadystatechange = function() {
if (script.readyState == 'loaded' || script.readyState == 'complete') {
script.onreadystatechange = null;
if (callback) callback();
}
};
} else { //Others
script.onload = function() {
if (callback) callback();
};
}
script.src = url;
document.getElementsByTagName('head')[0].appendChild(script);
}
// Usage:
loadScript('my-dynamic-script.js', function() {
console.log('my-dynamic-script.js loaded!');
// You can now use functions/variables defined in my-dynamic-script.js
});
Native JavaScript function to dynamically load a script with a callback.
script.onload
event is generally sufficient. The script.readyState
check is primarily for older versions of Internet Explorer.Using jQuery's $.getScript()
jQuery provides a convenient shorthand method, $.getScript()
, specifically designed for loading JavaScript files via AJAX GET requests. This method simplifies the process and automatically handles the script execution and callback.
// Using jQuery's $.getScript()
$.getScript('another-dynamic-script.js', function() {
console.log('another-dynamic-script.js loaded!');
// Code from another-dynamic-script.js is now available
});
// You can also chain .done(), .fail(), .always() for more control
$.getScript('yet-another-script.js')
.done(function(script, textStatus) {
console.log(textStatus + ': yet-another-script.js loaded!');
})
.fail(function(jqxhr, settings, exception) {
console.error('Failed to load yet-another-script.js:', exception);
});
Examples of dynamically loading scripts using jQuery's $.getScript()
.
$.getScript()
is convenient, it's important to remember that it relies on jQuery being present on the page. If you're building a vanilla JavaScript application, the native methods are more appropriate.Considerations and Best Practices
When dynamically loading scripts, keep the following in mind:
- Error Handling: Always include error handling (e.g.,
script.onerror
or jQuery's.fail()
) to gracefully manage situations where a script fails to load. - Order of Execution: If your dynamically loaded scripts have dependencies, ensure they are loaded in the correct order. You might need to chain
loadScript
calls or use promises. - Caching: Browsers typically cache dynamically loaded scripts. If you need to ensure a fresh version, you might append a unique query parameter (e.g.,
?v=timestamp
) to the script URL, though this can bypass legitimate caching. - Security: Be cautious when loading scripts from external, untrusted sources, as this can introduce security vulnerabilities (Cross-Site Scripting - XSS).
- Performance Impact: While dynamic loading improves initial load, loading too many scripts dynamically can still impact performance if not managed well. Consider bundling critical scripts and dynamically loading only truly optional ones.
sequenceDiagram participant Browser participant Server Browser->>Server: Request index.html Server-->>Browser: Send index.html (with base JS) Browser->>Browser: Render page, execute base JS Browser->>Browser: User interaction / Condition met Browser->>Server: Dynamically Request optional.js Server-->>Browser: Send optional.js Browser->>Browser: Execute optional.js Browser->>Browser: New functionality available
Sequence diagram showing the interaction between browser and server during dynamic script loading.