Home Code Remove a CSS File from a webpage dynamically

Remove a CSS File from a webpage dynamically

1105
0

It’s actually quite easy to remove a CSS or JS file from a webpage dynamically, it’s a little Javascript function:

function removejscssfile(filename, filetype)
{
var targetelement=(filetype==”js”)? “script” : (filetype==”css”)? “link” : “none” //determine element type to create nodelist from
var targetattr=(filetype==”js”)? “src” : (filetype==”css”)? “href” : “none” //determine corresponding attribute to test for
var allsuspects=document.getElementsByTagName(targetelement)
for (var i=allsuspects.length; i>=0; i–)
{ //search backwards within nodelist for matching elements to remove
if (allsuspects[i] && allsuspects[i].getAttribute(targetattr)!=null && allsuspects[i].getAttribute(targetattr).indexOf(filename)!=-1)
allsuspects[i].parentNode.removeChild(allsuspects[i]) //remove element by calling parentNode.removeChild()
}
}

After you have the function either declared in a file which you Include onto the webpage or written out in full inside a SCRIPT tag, you can call it like so:

<script language=”javascript” type=”text/javascript”>
         removejscssfile(“somescript.css”, “css”); //or js javascript file, etc
</script>

For much more information, please see this excellent site: http://www.javascriptkit.com/javatutors/loadjavascriptcss2.shtml

LEAVE A REPLY

Please enter your comment!
Please enter your name here