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:
(function($){
!$.test && $.test= function(){
alert('test');
}
})(jQuery);
jQuery.test();
!$.test
evaluates to true
if $.test
is 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:
$.test = $.test || function() {
alert('test');
}
This does the same thing actually. If $.test
is 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 type function
.
Have you tried something like this?
if(typeof $.test == "undefined") {
(function($){
$.test= function(){
alert('test');
}
})(jQuery);
jQuery.test();
}
(function($){
$.test = function() {
if (!$.test.hasBeenRun) {
$.test.hasBeenRun = true;
alert('test');
}
}
$.test.hasBeenRun = false;
})(jQuery);
jQuery.test();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With