In my web app, I want to conditionally import an external script based on some logic. I tried using document.createElement()
to append a <script>
tag, but although the script appears in the DOM, it’s not accessible or executed in the current file.
What’s the proper way to handle JavaScript load script dynamically?
I’ve handled conditional loading like this:
javascript
Copy
Edit
if (shouldLoadScript) {
var script = document.createElement('script');
script.src = 'https://example.com/your-script.js';
script.onload = function () {
console.log('Script loaded and ready to use!');
// You can now call functions from the loaded script
};
document.head.appendChild(script);
}
Make sure you’re using the onload event to ensure the script is available before you use it.
It’s a clean and pure way to load JavaScript dynamically without needing jQuery.
@apksha.shukla If you’re okay with jQuery, $.getScript() is super handy:
javascript
Copy
Edit
if (shouldLoadScript) {
$.getScript('https://example.com/your-script.js')
.done(function(script, textStatus) {
console.log('Script loaded:', textStatus);
// You can safely call functions from the script here
})
.fail(function(jqxhr, settings, exception) {
console.error('Script load failed:', exception);
});
}
This abstracts away all the DOM manipulation and makes JavaScript script loading feel seamless, especially in dynamic apps.