16

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.

2
  • 6
    When the JavaScript is parsed, it's added to the global scope (window object). So the element is just a text container. Commented Feb 9, 2015 at 17:56
  • 1
    Once javascript is executed, it's not as easy as just removing the script to make it un-execute Commented Feb 9, 2015 at 18:02

1 Answer 1

11

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.