Skip to content

Instantly share code, notes, and snippets.

@seanemmel-ba
Created November 20, 2015 16:03
Show Gist options
  • Save seanemmel-ba/e78ecb2c1bea1ea93af1 to your computer and use it in GitHub Desktop.
Save seanemmel-ba/e78ecb2c1bea1ea93af1 to your computer and use it in GitHub Desktop.
Helper function to poll for DOM els that don't exist on page load (helpful for Optimization platforms). The `this` context is set to the element you poll for in your callback function. Interval times out after 10s by default to prevent endless polling.
/**
* @package N/A
* @version 1.0
* @author Blue Acorn <[email protected]>, Sean Emmel <[email protected]>
* @copyright Copyright © 2015 Blue Acorn.
*/
/**
* @param {String} - the CSS selector for your element in question
* @param {Integer} - number of milliseconds to keep running the polling. Set low values (10ms)
for rapid polling. Set higher times (100ms) for more performance benefiting
polling. Lower times will help prevent flicker in optimization platforms,
but may impact performance.
@param {Function} - an optional callback function to run after the element has been found.
The `this` reference will be set to the element you are polling for.
Thus, in jQuery, $(this) will be the jQuery object of the CSS selector
you passed in as the first parameter.
*
*
* SAMPLE USAGE
-------------
Poll for any element that matches CSS selector '.thumbnail' every 10ms and then hide
said element(s) when found:
pollForElement('.thumbnail', 10, function() {
// $(this) will refer to $('.thumbnail') in question
$(this).hide();
});
*
*/
function pollForElement(el, time, callback) {
var interval = setInterval(function() {
if ($(el).length > 0 && $(el).is(':visible')) {
clearInterval(interval);
if (callback && typeof callback === 'function') {
callback.call($(el));
}
}
}, time);
/* Clear interval after 10s as a fallback */
setTimeout(function() {
clearInterval(interval);
}, 10000);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment