script tag create with innerHTML of a div doesn't work
This one was trivial.
As stated in spec (8.4 Parsing HTML fragments and 8.2.3.5 Other parsing state flags,) quote:
when using innerHTML
the browser will
Create a new Document node, and mark it as being an HTML document.
If there is a context element, and the Document of the context element is in quirks mode, then let the Document be in quirks mode.
Otherwise, if there is a context element, and the Document of the
context element is in limited-quirks mode, then let the Document be in
limited-quirks mode. Otherwise, leave the Document in no-quirks mode.Create a new HTML parser, and associate it with the just created Document node.
...
and when parsing a <script>
inside
The scripting flag is set to "enabled" if scripting was enabled for
the Document with which the parser is associated when the parser was
created, and "disabled" otherwise.The scripting flag can be enabled even when the parser was originally
created for the HTML fragment parsing algorithm, even though script
elements don't execute in that case.
So it won't be executed, as long as you inject it with innerHTML
.
And using innerHTML
will prevent the <script>
element created from being executed permanently.
As stated in spec (4.3.1 The script element,) quote:
Changing the src, type, charset, async, and defer attributes dynamically has no direct effect; these attribute are only used at specific times described below.
Concluding the described below is that, it only parse the src
attribute when injecting the <script>
to the document
(no matter which, including the temporary one created when using innerHTML
.)
So, as long as you want to inject a script to the document and make it executed, you have to use script = document.createElement('script')
.
Set its attributes like src
and type
, possibly the contents inside (by using script.appendChild(document.createTextNode(content))
), then append it to the document.body
.
Javascript-Script tag with the parent of div tag can't be executed
There are several issues there:
div
is not a valid child element ofhead
- You've created a
script
element object, but then you're trying to useouterHTML
(a round-trip through textual markup) to add it to thediv
appendChild
has twod
s, not just one- There's no point to putting the script in a
div
The correct way would be:
var scriptTag= document.createElement("script");
scriptTag.type = "text/javascript";
scriptTag.src = "https://example.com/example.js";
document.head.appendChild(scriptTag); // Or append it to document.body, doesn't matter
If you really, really want it in a div
, you have to put that div
in body
(directly or nested):
var scriptTag= document.createElement("script");
scriptTag.type = "text/javascript";
scriptTag.src = "https://example.com/example.js";
var div = document.createElement("div");
div.appendChildD(scriptTag);
document.body.appendChild(div);
...which will work, but is pointless.
Can scripts be inserted with innerHTML?
You have to use eval() to execute any script code that you've inserted as DOM text.
MooTools will do this for you automatically, and I'm sure jQuery would as well (depending on the version. jQuery version 1.6+ uses eval
). This saves a lot of hassle of parsing out <script>
tags and escaping your content, as well as a bunch of other "gotchas".
Generally if you're going to eval()
it yourself, you want to create/send the script code without any HTML markup such as <script>
, as these will not eval()
properly.
innerHTML for div doesn't work if script is seperated
You should be assigning the actual function to window.onload
but instead you are invoking the function and assigning the return value which is undefined:
Change
window.onload=go()
To
window.onload=go;
It only appears to work properly in the second version since the element referenced in the function already exists but it is not actually waiting for the load event to occur.
Why can't I add a string containing a script tag to innerHTML in IE
You could try to do something like this instead:
function loadScript(src) {
var script = document.createElement("script");
script.type = "text/javascript";
document.getElementsByTagName("head")[0].appendChild(script);
script.src = src;
}
or do
..
div.innerHTML = "<script src=\"somescript.js\"></script>";
..
How to insert and execute script tag to the DOM using plain js
You can use insertAdjacentHTML
to insert the HTML, then go back and look for the scripts and copy the script src
or text, and insert the copy into the DOM to run it:
// Sticking with broadly-supported features:var htmlString = "<div><h1>Title</h1></div><div><script>console.log('it works');<\/script></div>";var target = document.getElementById("target");target.insertAdjacentHTML("beforeend", htmlString);var scripts = target.getElementsByTagName("script");while (scripts.length) { var script = scripts[0]; script.parentNode.removeChild(script); var newScript = document.createElement("script"); if (script.src) { newScript.src = script.src; } else if (script.textContent) { newScript.textContent = script.textContent; } else if (script.innerText) { newScript.innerText = script.innerText; } document.body.appendChild(newScript);}
<div id="target"></div>
Setting innerHTML of script element not working on IE8
I think your issue is that innerHTML is not intended for use on script tags.
var contentScript = document.createElement("script");
contentScript.setAttribute("id", "contentSCRIPT");
contentScript.text = "alert('test');";
document.getElementById("main").appendChild(contentScript);
Related Topics
How to Fix Blurry Text in My Html5 Canvas
Dynamically Creating HTML Elements Using JavaScript
How to Detect When a Page Exits Fullscreen
Select All Elements With a "Data-Xxx" Attribute Without Using Jquery
Is It Possible For Flex Items to Align Tightly to the Items Above Them
Instead of Using Prefixes I Want to Ask Site Visitors to Upgrade Their Browser
Should CSS Always Precede JavaScript
Detect a Finger Swipe Through JavaScript on the Iphone and Android
Which Equals Operator (== VS ===) Should Be Used in JavaScript Comparisons
How to Detect a Click Outside an Element
How to Get Browser Width Using JavaScript Code
Alternative For Deprecated Svg Pathseglist
How to Check Connection Type (Wifi/Lan/Wwan) Using Html5/JavaScript
Best Way to Detect That Html5 ≪Canvas≫ Is Not Supported
How to Force the Browser to Reload Cached CSS and JavaScript Files
Why JavaScript This.Style[Property] Return an Empty String