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.