简体   繁体   English

等待元素加载后再缓存

[英]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. 有一个元素添加得较晚,并且总是以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. wpadminbar元素是在加载此脚本后添加的元素,因此它总是空值。 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? 是否将它们包装在DOMContentLoaded函数或其他内容中?

thanks for any help! 谢谢你的帮助!

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. 将受影响的代码包装在DOMContentLoaded处理程序中,以便确保在代码运行之前已完全加载DOM。

  2. Don't try to cache the DOM element until right before the code actually needs it (eg don't cache in advance). 在代码真正需要它之前,不要尝试缓存DOM元素(例如,不要提前缓存)。

  3. Don't cache it at all. 根本不缓存它。 Just fetch the DOM element anytime its needed. 只需在需要时随时获取DOM元素。 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. 如果在执行函数时需要多个位置相同的DOM元素,则可以在函数中本地缓存它,但是通常不需要长期跨操作缓存它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM