saltcod
saltcod

Reputation: 2041

Wait for an element to be loaded before caching it

I'm trying to be more organized with my code. I have a main object and I'm adding methods to that object.

Issue is: I'm not sure how to cache my selectors. There's one that element that gets added late and always ends up being null. So I'm looking for best practice on doing this.

Here's where I am:

var stickyAd = {};

// cache the elements I'll need
stickyAd.primaryContent = document.getElementById('primary-content');
stickyAd.wpadminbar = document.getElementById('wpadminbar');


// Calculate the offset of an element from the top of the document
stickyAd.topOffset = function(el) {
    var rect = el.getBoundingClientRect(),
    scrollTop = window.pageYOffset || document.documentElement.scrollTop;
    return { top: rect.top + scrollTop };
};


// The rest of my methods
stickyAd.scrollDetect = function(){};

stickyAd.stickyOn = function(){};
stickyAd.stickyOff = function(){}

stickyAd.init = function(){
	stickyAd.scrollDetect();

};

// Finally, call init()
stickyAd.init();

That wpadminbar element is the one getting added after this script has loaded, so it always comes up null. So although this seems like a fairly specific question, I'm looking to see how to best organize this to protect against situations like this.

How do I cache selectors inside this object in a way that they'll be available at the proper time? Do I wrap them in a DOMContentLoaded function or something else?

thanks for any help!

Upvotes: 0

Views: 64

Answers (1)

jfriend00
jfriend00

Reputation: 707826

Here are three options:

  1. Wrap the affected code in a DOMContentLoaded handler so you're sure the DOM is fully loaded before the code runs.

  2. Don't try to cache the DOM element until right before the code actually needs it (e.g. don't cache in advance).

  3. Don't cache it at all. Just fetch the DOM element anytime its needed. This is the most foolproof and is usually more than adequate. You can cache it locally within a function if the same DOM element is needed multiple places during the execution of a function, but usually there is no need to cache it long term across operations.

Upvotes: 2

Related Questions