JQuery Singleton

I have something like a file: test.js:

(function($){ $.test= function(){ alert('test'); } })(jQuery); jQuery.test(); 

Now, if test.js is loaded twice on my page ie src = test.js in two different places, it gives a warning twice. I want it to be like a singleton. Any ideas on how to achieve this?

+6
javascript jquery
source share
4 answers

Use a conditional shortcut:

 (function($){ !$.test && $.test= function(){ alert('test'); } })(jQuery); jQuery.test(); 

!$.test evaluates to true if $.test not defined, and the code with permissions after && is executed. Otherwise, it will simply skip the part. Another useful template for this might look like this:

 $.test = $.test || function() { alert('test'); } 

It does the same thing really. If $.test already defined, it is used, otherwise assign an anonymous function to $.test . Both versions can (and probably should) be optimized, but not just check if they were defined, but also if they are of type function .

+7
source share

Have you tried something like this?

 if(typeof $.test == "undefined") { (function($){ $.test= function(){ alert('test'); } })(jQuery); jQuery.test(); } 
0
source share
 (function($){ $.test = function() { if (!$.test.hasBeenRun) { $.test.hasBeenRun = true; alert('test'); } } $.test.hasBeenRun = false; })(jQuery); jQuery.test(); 
0
source share

Why aren't you extracting this common code into a third file?

Other than that, it depends on what the code does. As a rule, you can wrap the entire function in a state and execute only "if the conflicting thing has not yet been completed.

0
source share

All Articles