How to Change Script Src Dynamically using JavaScript

                             *****                        
   On - 2023
   By - Apu Gorai
To change the src attribute of a <script> tag dynamically using JavaScript, you can use the setAttribute() method. Here is an example of how to use it.

Example : 

<script>
 let s = document.querySelector('script');
 s.setAttribute('src', '/main.js');
</script>
You can also use the createElement() method to create a new script element and insert it into the document.

Example :

<script>
 let n = document.createElement('script');
     n.src = '/main.js';
     n.type = 'text/javascript';
    document.head.appendChild(n);
</script>
You can also use the insertAdjacentElement() method to insert the new script element before an existing script element.

Example :

<script>
 let myS = document.querySelector('script');
 let n = document.createElement('script');
     n.src = '/main.js';
     n.type = 'text/javascript';
 myS.insertAdjacentElement('beforebegin', n);
</script>
You can also use the replaceChild() method to replace an existing script element with a new one.
<script>
 let myS = document.querySelector('script');
 let n = document.createElement('script');
     n.src = '/main.js';
     n.type = 'text/javascript';
 myS.parentNode.replaceChild(n, myS);
</script>
Read More»