1

I want to do something like document.currentScript.onload = function(){alert(0)};. Basically, executing some code after the current script is done executing. How would you do that?

Note that this is an inline script. I want to set the onload handler only under certain conditions that can be known during the execution of current script only.

What I have tried:

  1. The snippet above. This did not work and my guess is that you cannot set an onload handler on a currently executing script. My reasoning may be wrong though.
  2. document.write('\x3cscript>alert(0);\x3c/script>');. My hope was that the content of document.write would execute after the current script has finished execution. However, it seems that the content is executing as soon as it is written on the page stream.
r.v
  • 4,697
  • 6
  • 35
  • 57
  • The question is not a duplicate. See my edit. – r.v Dec 20 '17 at 22:25
  • So why not override a callback (*which by default does nothing*) that is called at the end of your script. – Gabriele Petrioli Dec 20 '17 at 22:29
  • Sure, that is an obvious solution. But I do not want to change the inline scripts. All the logic decision whether to do any code execution happens by overriding some DOM and Javascript native functions. – r.v Dec 20 '17 at 22:37
  • If there is some way to have some code execute after every `script` element is done executing (without modifying the `script`s themselves), that would be fine. – r.v Dec 20 '17 at 22:39

1 Answers1

0

The load event is fired only for external scripts (your code would work if it was inside an external script).

A Firefox only solution is to use the afterscriptexecute event.

<script id="first">
  document.addEventListener("afterscriptexecute", function(e){
    console.log(`Script "${e.target.id}" just finished executing`);
  }, true);
</script>
<script id="second">console.log('a log');</script>
<script id="third">console.log('another log');</script>
<script id="fourth">console.log('yet another log');</script>

Other than these, i can only think (as suggested in the comments) to use an empty callback which is overridden with your code if your conditions are met.

Something like

<script>
    let afterscriptexecute = function(){}; 
    
    // .. your code
    
    if (Math.random() < 0.5){ // if condition is met
       afterscriptexecute = function(){
         // do something
         alert('conditions were met');
       }
    }
    
    // end of your code
    
    afterscriptexecute();
</script>
    
    
Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317