Home Top Ad

How to execute a script by call his id

Share:

How to execute a script by call his id

That's not how JavaScript works.
Once you include a <script> in DOM, it's executed. However, the script itself can define functions, which could be named and called at a later point (by their name), by any other script or element in the page, as long as they have access to the context in which you defined your function.
Example:
<script>
  function myFunction() {
    window.alert('I got called!');
  }
</script>

<button onclick="myFunction()">Execute myFunction()</button>
So instead of using the id of the script, I'm using the name of the function.

To fully answer your question: running a script by id is not possible because all scripts are executed as soon as they are parsed by the browser (which happens in their chronological order in DOM) and there is no way of re-running them after they have already been executed.
Obviously, one could argue that you could remove the <script> tag altogether, create a new one with the same contents, which is going to be rerun when added to DOM. But, at least in theory, it's not rerunning the same <script>, it's running a different one. Another instance/<script> tag.
Needless to say, nobody does that as it's much more convoluted than to simply define a function and call that function at a later time.

Aucun commentaire