This question has been asked a few times on stackoverflow, but I have yet to come across a solution that suits my unique situation.
I'm looking to replace deprecated code livequery
and DOMNodeInserted
. Examples shown below.
I’m developing javascript for a 3rd party website we are required to use at work. Therefore, when my script is run the page has loaded and I have no access to the js file on the server. We use IE exclusively, the current version is IE11.
I’ve read here that livequery()
is useful in “rare case where you need to respond to DOM changes, and have no control over the jQuery that is causing those changes”. This is my situation exactly.
I am a complete noob with this stuff but I’ve read MutationEvents/Observers can do this, but they are not compatible with IE. What I’ve read is beyond my understanding at this point anyway.
Here is what I am trying to do:
When a user clicks a tab on the 3rd party app, everything on that tab is dynamically created. I need to determine when the tab has finished loading - so I do this by checking for the existence of an element on the tab, and when it is created I know the tab has loaded.
For this example, the tab includes an icon called 's_3_1_12_0_icon'.
Both of these code snippets will trigger the desired result:
//Method 1: Using DOMNodeInserted
$('body').on('DOMNodeInserted', function () {
var elementExists = document.getElementById('s_3_1_12_0_icon');
if (elementExists != null) {
alert('The element has just been created')
$('body').off('DOMNodeInserted');
}
});
//Method 2: Using Livequery
$('#s_3_1_12_0_icon').livequery(function() {
alert('The element has just been created')
$('#s_3_1_12_0_icon').expire();
});
But as mentioned, livequery()
and DOMNodeInserted
are depricated. Is there a modern method of doing this?
...I’ve read MutationEvents/Observers can do this, but they are not compatible with IE...
IE9 and IE10 both have the old deprecated mutation events (mostly); IE11 has the newer mutation observers. You can definitely use a mutation observer for this.
var observer = new MutationObserver(function() {
if (document.getElementById('s_3_1_12_0_icon') != null) {
var p = document.createElement('p');
p.innerHTML = "It fired!";
document.body.appendChild(p);
observer.disconnect();
observer = null;
}
});
observer.observe(document.body, {
childList: true,
subtree: true
});
setTimeout(function() {
var div = document.createElement('div');
div.id = "s_3_1_12_0_icon";
document.getElementById("descendant").appendChild(div);
}, 600);
<div>
<div>
<div id="descendant"></div>
</div>
</div>
<p>In a moment, we'll add the element and see if the observer fires...</p>
(The div
s are just there to demonstrate that it doesn't have to be a direct child of body
.)