It seems from my tests that a script tag can be removed from the DOM without any impact on the JavaScript that it contains.
This test destroys the script DOM nodes part way through execution. Even this has no effect on the script, the variable count
is assigned the value 1
after the script tag has been removed from the DOM.
<!DOCTYPE html>
<html lang="en">
<head>
<title> Test </title>
<script id="jQueryScriptTag" src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
</head>
<body>
<button id="testBtn">Click to test</button>
<div id="output"></div>
<script id="testCodeScriptTag">
var count;
$("#jQueryScriptTag").remove();
$("#testCodeScriptTag").remove();
$("#output").append(
"<p>jQueryScriptTag is " + document.getElementById("jQueryScriptTag") + "</p>" +
"<p>testCodeScriptTag is " + document.getElementById("testCodeScriptTag") + "</p>" +
"<p>count is " + count + "</p>"
);
count = 1;
$("#testBtn").click(function(){
$("#output").append(
"<p>count is " + (count++) + "</p>"
);
});
</script>
</body>
</html>
The use case is safely removing injected third-party script elements from the host site.
The <script> tag is used to embed a client-side script (JavaScript). The <script> element either contains scripting statements, or it points to an external script file through the src attribute. Common uses for JavaScript are image manipulation, form validation, and dynamic changes of content.
Dynamic script such as text/javascript . None, both the starting and ending tag are mandatory. Any element that accepts metadata content, or any element that accepts phrasing content.
External JavaScript Advantages Placing scripts in external files has some advantages: It separates HTML and code. It makes HTML and JavaScript easier to read and maintain. Cached JavaScript files can speed up page loads.
The script tag should always be used before the body close or at the bottom in HTML file. The Page will load with HTML and CSS and later JavaScript will load.
By the time the contents of #testCodeScriptTag
are executing they have already been fetched from the DOM, loaded into the JavaScript engine, and parsed. The text in the DOM is no longer in any way connected to the executing code, as required by the HTML 5 specification:
1. Initialize the script block's source as follows:
...
If the script is inline and the script block's type is a text-based language
The value of the text IDL attribute at the time the element's "already started" flag was last set is the script source.
...
4. Create a script, using the script block's source, the URL from which the script was obtained, the script block's type as the scripting language, and the script settings object of the script element's Document's Window object.
...
Note: This is where the script is compiled and actually executed.
See Also: http://www.w3.org/TR/html5/webappapis.html#creating-scripts
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With