Disabling External Integrated JavaScript Files Using JavaScript

Time: Column:Mobile & Frontend views:245

Problem:I have included the following in my <head> tag (Google AdSense). Now, I'm looking for a way to disable this line via JavaScript:

<script type="text/javascript" src="https://domain.tld/javascript-file.js"></script>
  1. Using CSS (e.g., display: none) doesn't work because the code will still be executed regardless.

  2. If this external JS defines some functionality, I want to use external JS to disable this line so that it won't be executed.

Solution:Write the following code before the <script> tag to remove the specific script tag before it executes:

window.addEventListener("load", function() {
    var scriptTags = document.getElementsByTagName('script');
    for (let idx = scriptTags.length - 1; idx >= 0; idx--) {
        if (scriptTags[idx].src == "https://domain.tld/javascript-file.js") {
            var parent = scriptTags[idx].parentNode;
            if (parent) parent.removeChild(scriptTags[idx]);
        }
    }
});

Explanation:This function only works if the script tag is part of the document structure and hasn’t run yet. Clearly, once the script has executed, it can no longer be removed.