thebeast22 thebeast22 - 1 year ago 86
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;

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 Source

you can check for script with src

if($('script[src="'+ url +'"]').length < 1){

var url = 'something.js';

if($('script[src="'+ url +'"]').length < 1){
   alert('script duplicated');
<script src=""></script>
<script src="something.js"></script>