How to change the "src" attribute of a <script> tag using Javascript?

Asked

Viewed 598 times

0

I want it from the same index.html can change your content using two files .js different. In short, I want to change the .js without changing page html, Type:

<html>
    <head>
    </head>
    <body>
        <button id="texto" onclick="function(){ dcoument.querrySelector('#teste').src = 'teste2.js'">Teste</button>
        <script id="teste"  src="teste1.js"></script>

    </body>

</html>

That’s possible, or something?

3 answers

1

Instead of document.querySelector('#teste'), you put dcoument.querrySelector('#teste')

<img src="exemplo.png">
<button type="button">Mudar imagem</button>

<script>
    const button = document.querySelector('button')

    button.addEventListener('click', function () {
        const imagem = document.querySelector('img')
        imagem.src = 'exemplo2.png'

        event.preventDefault()
    })
</script>

1


Just changing the src of the tag will not load the new script into memory or run it, ie it will not cause any effect. And even after loading the script teste1.js you will not be able to erase it from memory while the page is open.

What you could do is dynamically create a new tag script with the teste2.js. There is the code of teste2.js will be loaded into memory. Add new tag with .createElement() and .appendChild():

<button id="texto" onclick="var scr = document.createElement('script');
   scr.src = 'teste2.js'; document.body.appendChild(scr)">Teste</button>
  • Thank you very much XD

0

To change the attribute of a tag script, you need to use the method setAttribute, passing as parameter the desired attribute and the value.

const script = document.querySelector('script');
script.setAttribute('src', 'file.example.js');

Browser other questions tagged

You are not signed in. Login or sign up in order to post.