Client-Side Dynamic Removal of <script> Tags in <head>
Posted
by
merv
on Stack Overflow
See other posts from Stack Overflow
or by merv
Published on 2012-10-05T14:07:40Z
Indexed on
2012/10/08
21:37 UTC
Read the original article
Hit count: 218
Is it possible to remove script tags in the <head>
of an HTML document client-side and prior to execution of those tags?
On the server-side I am able to insert a <script>
above all other <script>
tags in the <head>
, except one, and I would like to be able to remove all subsequent scripts. I do not have the ability to remove <script>
tags from the server side.
What I've tried:
(function (c,h) {
var i, s = h.getElementsByTagName('script');
c.log("Num scripts: " + s.length);
i = s.length - 1;
while(i > 1) {
h.removeChild(s[i]);
i -= 1;
}
})(console, document.head);
However, the logged number of scripts comes out to only 1, since (as @ryan pointed out) the code is being executed prior to the DOM being ready. Although wrapping the code above in a document.ready
event callback does enable proper calculation of the number of <script>
tags in the <head>
, waiting until the DOM is ready fails to prevent the scripts from loading.
Is there a reliable means of manipulating the HTML prior to the DOM being ready?
Background
If you want more context, this is part of an attempt to consolidate scripts where no option for server-side aggregation is available. Many of the JS libraries being loaded are from a CMS with limited configuration options. The content is mostly static, so there is very little concern about manually aggregating the JavaScript and serving it from a different location. Any suggestions for alternative applicable aggregation techniques would also be welcome.
© Stack Overflow or respective owner