udhavsethi
udhavsethi

Reputation: 83

Script parsed using DOMParser does not execute

When I create a script element using document.createElement and append it to document.head, the JavaScript executes successfully:

var el = document.createElement('script');
el.text = "console.log('Hello World!')";
document.head.insertAdjacentElement('afterbegin', el);
// console output: "Hello World!"

But if I use a DOMParser to parse an html string and then append its firstElementChild to document.head, the JavaScript does not execute:

var parser = new DOMParser();
var htmlString = "<script>console.log('Bye World!')<\/script>";
var domEl = parser.parseFromString(htmlString, "text/xml").firstElementChild;
document.head.insertAdjacentElement('afterbegin', domEl);
// No console output

A <script> tag is added to document.head in both the cases. Why does the JavaScript not execute in the second case?

Upvotes: 5

Views: 1576

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075457

Because the DOMParser marks the script element so that it won't be run, since the DOMParser parses text/xml (and others) with scripting disabled (spec). Whether the script should be run is a piece of state information associated with the script element, which is why this doesn't run the script twice:

var el = document.createElement('script');
el.text = "console.log('Hello World!')";
document.head.insertAdjacentElement('afterbegin', el);
document.head.removeChild(el);
document.head.appendChild(el);

Upvotes: 4

Related Questions