I have written the following block of code and it works in my scenario but I know it is dirty:
var navbarModule = (function($) {
var self = {};
var $login;
self.hideLogin = function() {
$login.hide();
};
self.showLogin = function() {
$login.show();
};
$(document).ready(function() {
$login = $(".navbar-form");
});
return self;
}(jQuery));
My goals for the code are:
- Only select the DOM element if necessary
- Cache the selected DOM element
- Guarantee that the cached DOM element exists
My code fails to achieve #1, achieves #2, and circumstantially achieves #3. I.e., for requirement #3, navbarModule.hideLogin() works if the DOM has fully loaded but does not if you call it before the navbar is present in the DOM.
Is there a way to achieve true lazy loading and caching that meets my goals without circumstantially working?