How to insert a script tag dynamically
Mar 24, 2021
Say you need to include a regular ol’ script
tag in a template file based on a global variable being set or not. Well, here’s a snippett you can use.
<script type="text/javascript">if (window.libName) { const script = document.createElement('script') script.src = "https://cdn.com/js/lib-" + window.libName + ".min.js" document.body.appendChild(script);}</script>
This will add a script tag with a src
value that is produced by combining a value from window.libName
and combining it with .min.js
to create the proper path needed. After this is done, the script tag is loaded into the document using appendChild.