Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if Javascript script exists on page

Tags:

javascript

I have a bookmarklet that I've made and it loads a script from my server onto the users current page. However I have an if check in my script that if a condition is not met then no action is taken. However if the user then meets that condition then the code is run, but has caused there to be two sets of scripts inserted into their page. Can i prevent this?

 <a href="javascript: (function () {     var jsCode = document.createElement('script');     jsCode.setAttribute('src', 'http://xxx.co.uk/xxx/script.js');   document.body.appendChild(jsCode);  }());">Bookmarklet</a> 
like image 421
benhowdle89 Avatar asked Mar 11 '12 21:03

benhowdle89


People also ask

How do I check if a Javascript script is loaded?

To detect if the script has already loaded, I use the following method (in general): Create a common library function to dynamically load all scripts. Before loading, it uses the isScriptLoaded(src) function above to check whether the script has already been added (say, by another module).

How do I ensure Javascript is loaded?

What is the best way to make sure javascript is running when page is fully loaded? If you mean "fully loaded" literally, i.e., all images and other resources downloaded, then you have to use an onload handler, e.g.: window. onload = function() { // Everything has loaded, so put your code here };


1 Answers

You can check whether your script is loaded like this:

function isMyScriptLoaded(url) {     if (!url) url = "http://xxx.co.uk/xxx/script.js";     var scripts = document.getElementsByTagName('script');     for (var i = scripts.length; i--;) {         if (scripts[i].src == url) return true;     }     return false; } 

Alternatively, you could do something like this:

<a href="javascript:     if (!jsCode) {         var jsCode = document.createElement('script');         jsCode.setAttribute('src', 'http://xxx.co.uk/xxx/script.js');         document.body.appendChild(jsCode);     }  ">Bookmarklet</a> 

This "pollutes" the global namespace with the jsCode variable, but that might be a necessary evil. You could rename it to something that is unlikely to appear in the document where the bookmarklet is run.


Please note that while the javascript URI scheme is okay for bookmarklets as in this case, it's not considered to be a good practice for normal use.

like image 177
Dagg Nabbit Avatar answered Sep 21 '22 17:09

Dagg Nabbit