-
Notifications
You must be signed in to change notification settings - Fork 2
/
jquery.elementReady.js
72 lines (61 loc) · 1.93 KB
/
jquery.elementReady.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/**
* jquery.elementReady.js
* jQuery plugin which fires a callback when an element is added to the DOM
* Jan Míšek <jan.misek@rclick.cz>
* License: MIT
*
* Usage:
*
* ```
* $(element).elementReady('.class', function() {
* console.log('element of given selector .class is added or already existed in the DOM');
* });
* ```
*
*/
/* global JQuery */
(function ($) {
$.fn.elementReady = function (selector, callback, options) {
options = $.extend({
exception: true,
one: true
}, options || {});
// are elements in DOM already
var elements = $(selector);
if (elements.length) {
callback(elements);
return this;
}
// not, try to use mutation observer, first check for browser availability
if (typeof MutationObserver === undefined || !MutationObserver) {
if (options.exception) {
throw new Error('browser does not support mutation observers');
} else {
return this;
}
}
// Compatibile, lets use mutation observer
var observer = new MutationObserver(function (mutations) {
mutations.some(function (mutation) {
if (mutation.addedNodes) {
var elements = $(mutation.addedNodes).find(selector);
if (elements.length) {
if (options.one) {
observer.disconnect();
}
callback(elements);
return true;
}
}
}.bind(this));
}.bind(this));
// do observation
observer.observe(this.get(0), {
childList: true,
subtree: true,
attributes: true,
characterData: false
});
return this;
};
}(jQuery));