Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Using Mutation Observers to Watch for Element Availability
'use strict';
var listeners = [],
doc = win.document,
MutationObserver = win.MutationObserver || win.WebKitMutationObserver,
function ready(selector, fn){
// Store the selector and callback to be monitored
selector: selector,
fn: fn
// Watch for changes in the document
observer = new MutationObserver(check);
observer.observe(doc.documentElement, {
childList: true,
subtree: true
// Check if the element is currently in the DOM
function check(){
// Check the DOM for elements matching a stored selector
for(var i = 0, len = listeners.length, listener, elements; i < len; i++){
listener = listeners[i];
// Query for elements matching the specified selector
elements = doc.querySelectorAll(listener.selector);
for(var j = 0, jLen = elements.length, element; j < jLen; j++){
element = elements[j];
// Make sure the callback isn't invoked with the
// same element more than once
element.ready = true;
// Invoke the callback with the element, element);
// Expose `ready`
win.ready = ready;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment