I have something like in a file say test.js:
(function($){
$.test= function(){
alert('test');
}
})(jQuery);
jQuery.test();
Now if test.js is loaded twice in my page i.e. src=test.js in two different locations, it gives alert twice. I want it to be like a singleton. Any ideas on how to achieve this?
Use a conditional shortcut:
!$.testevaluates totrueif$.testis not defined and the code on the rightside after the&&is executed. Otherwise, it’ll just skip the part. Another useful pattern for that could look like:This does the same thing actually. If
$.testis already defined its used, otherwise assign the anonymous function to$.test. Both versions can (and probably should) get optimized but not just checking if they were defined, but also if they are from typefunction.