How to Disable an External JavaScript File

disable external javascript file with javascript
10 November 2024

In summary, you can disable a JavaScript file that is connected to your page externally...

Using DOM to Remove Script

One of the simple methods for disabling a JavaScript file...

<script>
var scriptTags = document.getElementsByTagName('script');
for (var i = 0; i < scriptTags.length; i++) {
    if (scriptTags[i].src.includes('external-file.js')) {
        scriptTags[i].parentNode.removeChild(scriptTags[i]);
    }
}
</script>

Line-by-Line Explanation of the Code

var scriptTags = document.getElementsByTagName('script');
This line collects all <script> tags in the HTML document.
for (var i = 0; i < scriptTags.length; i++)
A loop iterates through all existing scripts in the document.
if (scriptTags[i].src.includes('external-file.js'))
This checks whether the script's src contains the file name 'external-file.js'.
scriptTags[i].parentNode.removeChild(scriptTags[i])
If the condition is true, the script will be removed from the DOM.

FAQ

?

How can I disable a JavaScript file?

?

Can this method be used for internal JavaScript files as well?