Chrome Extension: Waiting For Element to Load (async js)
<p>I have a Chrome extension, and I want to wait until an element is loaded before injecting content into the page.</p>

<p>I'm trying to inject a button:</p>

<pre><code>myButton = document.createElement('button');
myButton.class = 'mybutton';
document.querySelector('.element_id').appendChild(myButton)
</code></pre>

<p>I have this at the top of my content script. It used to work just fine, but then it stopped working. The error that was displayed was:</p>

<p><code>Uncaught TypeError: Cannot read property 'appendChild' of null</code></p>

<p>In order to wait for the element with class id <code>.element_id</code> to load, I tried to use a MutationObserver</p>

<pre><code>var observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {
        if (!mutation.addedNodes) return

        for (var i = 0; i &lt; mutation.addedNodes.length; i++) {
            if (mutation.addedNodes[i].parentNode == document.querySelector('#outer-container')) {

                myButton = document.createElement('button');
                myButton.class = 'mybutton';
                document.querySelector('.element_id').appendChild(myButton)
        }
            var node = mutation.addedNodes[i]
        }
    })
})

observer.observe(document.body, {
    childList: true
    , subtree: true
    , attributes: false
    , characterData: false
})
</code></pre>

<p>When I used the mutation observer, the page would load an outer div element called <code>outer-container</code>, and there was no way for me to directly compare the class <code>.element_id</code>. The class <code>.element_id</code> is nested a number of layers into the outer div.</p>

<p>HOWEVER, the above did not work, and I still received the null property error.</p>

<p>Is there a better way to wait for some element to be loaded (which is loaded async), before injecting?</p>