Some third party javascript is included in my HTML page. It adds some sharing buttons to my webpage, and is called as like
<script src=http://something/something.js></script>
But sometimes I would like not to load this javascript at all. It could be solved on the server side, which would block, under some conditions, the above mentioned line from appearing at the webpage. But this is not possible to remove this tag from the HTML at all due to technical reasons, neither by server side (like PHP) nor by javascript (eg. by using document.write to put the tag there only when needed). I need to resolve this in javascript only, and I need to BLOCK the script tag if condition is met, meaning the tag always exists in the HTML.
Is there any possibility to block the something.js URL mentioned above from loading? So I would, for example, execute some other javascript before or after it. I thought that it would be possible this way, but it doesn't seem to work:
<script>
(function(){
var scripts=document.getElementsByTagName('script');
for (var i=0; i<scripts.length; i++)
if (scripts[i].src && scripts[i].src=='http://something...')
scripts[i].parentNode.removeChild(scripts[i]);
})();
</script>
<script src=http://something/something.js></script>
This doesn't work because when the script is called, it cannot see another <script>
tag below at that moment. If I put the script below, it detects the script with src attribute, but it is too late to remove the element since it has already executed (and pasted sharing button elements to the webpage).
Is there any other way to stop loading of the third party script? Thank you
EDIT: updated the fact that the third party javascript needs to be in the HTML every time due to some internal reasons (despite the fact I disagree with that, I can do nothing about it).
a simple solution could be:
<script>
if(yourcondition){
document.write('<script src=\"http://something/something.js\" type=\"text/javascript\"><\/script>');
}
else{
document.write('<script src=\"http://something/OTHER.js\" type=\"text/javascript\"><\/script>');
}
</script>
yourcondition
can be a boolean stored in a cookie or localstorage. Or you can set it to true
or false
depending your needs.
Also note that the source value in your script tag must be encapsulated between "
If the script relies on being in the document during the initial parsing because it outputs HTML where it appears (e.g., via document.write
), as it seems to from your hidemeifnecessary
example, then your "hide me" approach is probably the best you can do client-side.
If the script didn't need to be in the page during the main parsing, you could lazy-load it, but from your question that doesn't seem to be the case.
As you said in the question, the right answer here really is to deal with this server-side.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With