6

Is it guaranteed that this code

function runEmbeddedJSInPageEnvironment(code) {
  var e = document.createElement('script');
  e.type = 'text/javascript';
  e.appendChild(document.createTextNode(code));
  (document.head || document.documentElement).appendChild(e);
  e.parentNode.removeChild(e);
}

runEmbeddedJSInPageEnvironment("$('#someform').off('submit');");

will wait for the code passed to the runEmbeddedJSInPageEnvironment to finish first, and only then remove it from the page by calling removeChild function?

Or can it be removed before this code finished to execute?

FrozenHeart
  • 19,844
  • 33
  • 126
  • 242
  • I think it depends on browsers – llamerr Mar 30 '16 at 11:17
  • 1
    better be sure and add `scr.onload` - http://stackoverflow.com/questions/1293367/how-to-detect-if-javascript-files-are-loaded (and remove child afterwards) – llamerr Mar 30 '16 at 11:20
  • I would use the queue as in here - http://stackoverflow.com/questions/899102/how-do-i-store-javascript-functions-in-a-queue-for-them-to-be-executed-eventuall – Velimir Tchatchevsky Mar 30 '16 at 11:24

1 Answers1

4

Yes, according to HTML5 the code will run before removing the script element.

When you insert it into the document, it's immediately prepared:

When a script element that is not marked as being "parser-inserted" experiences one of the events listed in the following list, the user agent must synchronously prepare the script element:

At step 15 of the prepare a script algorithm, since the script doesn't have a src attribute and has not been flagged as "parser inserted", your case would be the last one:

Otherwise: The user agent must immediately execute the script block, even if other scripts are already executing.

But of course, if that script has asynchronous code like setTimeout, that will be postponed.

Oriol
  • 274,082
  • 63
  • 437
  • 513