Can I load a javascript file conditionally by using select tag in html code?

Is it possible to load different javascript files inside the same web page by using select tag in the html code?
Thank you!

It’s… possible, yes, though I’d question the why.

I want to save some javascript snippets for personal use, that’s all.

Unless said snippets define the same function names, there would be no necessity to load them via select - you’d just load all of the script files via <script> tags

Hi @stavroskefaleas, you can dynamically create script tags and append them to the document.body like so:

const script = document.createElement('script')

script.src = 'url/to/script.js'
document.body.appendChild(script)

One compelling reason would be to only load modules on demand… that’s the motivation for the import() syntax, and for example webpack goes great lengths to achieve code splitting and lazy loading. Although it appears that this is not what the OP is after. ^^

2 Likes

Just be careful doing that if the scripts in question invoke action binders… putting a load function unchecked onto a form element that might receive the same value multiple times can have unintended consequences…

1 Like

though I’d question the why.

This is fairly common practice with large SPAs. Webpack can do conditional code splitting and I’ve used Script.js to do the same thing in a React app before the Webpack support was there.

Here is an official React tutorial that leverages Webpack code splitting, if you want to see how it can be used: https://reactjs.org/docs/code-splitting.html#route-based-code-splitting

(this comment is not really relevant to OP)

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.