How do you disable <script> elements using JavaScript

You can disable a script element. There are a couple of ways:

You can specify a different script type as other have listed. Heres the one that worked for me:

//loop through all script tags on page
$('script').each(function(){
    var scripthtml = $(this).html();
    $(this).replaceWith('<script type="text/gzip">' + scripthtml + '</script>');
});

All of the official script types can all be found here: iana.org

The second way is just a simple if statement:

//loop through all script tags on page
$('script').each(function(){
    var scripthtml = $(this).html();
    $(this).replaceWith('<script>if (1==0){' + scripthtml + '}</script>');
});

The if statement will always be false, so anything inside the script tag won't execute. However all of your functions() inside the script tag will all be valid.

Heres the javascript equivalent of replaceWith:

//get script and html
var yourscripttag = document.getElementById('yourscripttagID');
var scripthtml = 'if (1==0){' + yourscripttag.innerHTML + '}';
//remove script
yourscripttag.remove();
//create new script element
var newscript=document.createElement('script');
newscript.type='text/javascript';
//insert html in new script tag
newscript.appendChild(document.createTextNode(scripthtml));
//insert new script tag into head
document.getElementsByTagName('head').item(0).appendChild(newscript);

In fact, it is possible to disable execution by changing "type" attribute:

<script type="text/javascript">
    alert("I will alert you");
</script>

<script type="application/json">
    alert("And I will keep silent");
</script>

<script>
    alert("I will alert too");
</script>

http://jsfiddle.net/r6c0x0sc/


Can't be done... A script tag evaluates as soon as the DOM renderer renders it, so getting a handle on it after wards won't do much.

Tags:

Javascript

Dom