1

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?

Community
  • 1
  • 1
thebeast22
  • 103
  • 3
  • 11
  • 2
    *"and then remove it if true?"* - I don't think you want to *remove* duplicates, you want to not add duplicates in the first place. – nnnnnn Jul 04 '16 at 02:38
  • 1
    Yes. Simply iterate through the list of scripts on the page each time'd like to add a new one, If any of them have `.src` equal to the `src` to be added,skip. `document.getElementsByTagName('script')` will get the list you need. – enhzflep Jul 04 '16 at 02:40

3 Answers3

1

Keep track of the scripts you're appending and do not add once twice. You don't want to remove scripts, you simply want to prohibit them from being added more than once.

Lifz
  • 690
  • 6
  • 10
1

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>
Mohamed-Yousef
  • 23,946
  • 3
  • 19
  • 28
0

You can check using following code -

$(document).ready(function(){
   var exists = $('script[src="'+URL+'"]').length;
   if(exists>0){
         //already exists
   }else{
        //append new 
   }    
});

https://jsbin.com/cogocanoji/edit?html,css,js,console,output

Arvind
  • 1,006
  • 10
  • 16