thebeast22 thebeast22 - 5 months ago 31
jQuery Question

How to remove duplicated scripts in an HTML head?

I am appending external scripts inside the head tag using the following code which I got here: How to Append <script></script> in javascript?.

var s = document.createElement("script");
s.type = "text/javascript";
s.src = url;
$("head").append(s);




It works fine, except for that sometimes, the script that I am appending is already duplicated, hence affecting the logic of the page.

Is there anyway to check for duplicate external scripts and then remove it if true?

Answer

you can check for script with src

if($('script[src="'+ url +'"]').length < 1){
   $("head").append(s);
}

var url = 'something.js';


if($('script[src="'+ url +'"]').length < 1){
   //$("head").append(s);
   alert('append');
}else{
   alert('script duplicated');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="something.js"></script>