Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will injected JS code finish before removing

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?

like image 594
FrozenHeart Avatar asked Mar 30 '16 11:03

FrozenHeart


People also ask

Is JS executed from top to bottom?

In interpreted languages, the code is run from top to bottom and the result of running the code is immediately returned. You don't have to transform the code into a different form before the browser runs it.

Which function is responsible for code to execute only once after some specific duration?

The function setTimeout is called with 2 arguments: a message to add to the queue, and a time value (optional; defaults to 0 ). The time value represents the (minimum) delay after which the message will be pushed into the queue.

Why do we have to separate the JS file from HTML?

It separates HTML and code. It makes HTML and JavaScript easier to read and maintain.


1 Answers

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:

  • The script element gets inserted into a document, at the time the node is inserted according to the DOM, after any other script elements inserted at the same time that are earlier in the Document in tree order.

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.

like image 139
Oriol Avatar answered Oct 08 '22 10:10

Oriol