요소가 존재할 때까지 기다리는 방법? 알아내는 가장 좋은 방법은 무엇입니까?

Chrome에서 확장 프로그램을 개발 중이며 요소가 언제 존재하는지 알아내는 가장 좋은 방법은 무엇입니까? 요소가 존재할 때까지 확인하는 간격으로 일반 자바 스크립트를 사용하거나 jQuery가 이것을 수행하는 쉬운 방법이 있습니까?



답변

DOMNodeInserted성능 문제로 인해 다른 DOM 돌연변이 이벤트와 함께 더 이상 사용되지 않습니다. 권장되는 방법은 MutationObserver 를 사용 하여 DOM을 보는 것입니다. 최신 브라우저에서만 지원되므로 사용할 수없는 DOMNodeInserted경우 MutationObserver에는 다시 넘어야 합니다.

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

    for (var i = 0; i < mutation.addedNodes.length; i++) {
      // do things to your newly added nodes here
      var node = mutation.addedNodes[i]
    }
  })
})

observer.observe(document.body, {
    childList: true
  , subtree: true
  , attributes: false
  , characterData: false
})

// stop watching using:
observer.disconnect()

답변

나는이 같은 문제를 겪고 있었기 때문에 플러그인 을 작성했다.

$(selector).waitUntilExists(function);

암호:

;(function ($, window) {

var intervals = {};
var removeListener = function(selector) {

    if (intervals[selector]) {

        window.clearInterval(intervals[selector]);
        intervals[selector] = null;
    }
};
var found = 'waitUntilExists.found';

/**
 * @function
 * @property {object} jQuery plugin which runs handler function once specified
 *           element is inserted into the DOM
 * @param {function|string} handler
 *            A function to execute at the time when the element is inserted or
 *            string "remove" to remove the listener from the given selector
 * @param {bool} shouldRunHandlerOnce
 *            Optional: if true, handler is unbound after its first invocation
 * @example jQuery(selector).waitUntilExists(function);
 */

$.fn.waitUntilExists = function(handler, shouldRunHandlerOnce, isChild) {

    var selector = this.selector;
    var $this = $(selector);
    var $elements = $this.not(function() { return $(this).data(found); });

    if (handler === 'remove') {

        // Hijack and remove interval immediately if the code requests
        removeListener(selector);
    }
    else {

        // Run the handler on all found elements and mark as found
        $elements.each(handler).data(found, true);

        if (shouldRunHandlerOnce && $this.length) {

            // Element was found, implying the handler already ran for all 
            // matched elements
            removeListener(selector);
        }
        else if (!isChild) {

            // If this is a recurring search or if the target has not yet been 
            // found, create an interval to continue searching for the target
            intervals[selector] = window.setInterval(function () {

                $this.waitUntilExists(handler, shouldRunHandlerOnce, true);
            }, 500);
        }
    }

    return $this;
};

}(jQuery, window));

답변

다음은 요소 표시를 기다리는 핵심 JavaScript 함수입니다.

매개 변수 :

  1. selector:이 함수는 $ {selector} 요소를 찾습니다.
  2. time:이 함수는이 요소가 $ {time} 밀리 초마다 존재하는지 확인합니다.

    function waitForElementToDisplay(selector, time) {
            if(document.querySelector(selector)!=null) {
                alert("The element is displayed, you can put your code instead of this alert.")
                return;
            }
            else {
                setTimeout(function() {
                    waitForElementToDisplay(selector, time);
                }, time);
            }
        }

예를 들어, 설정 selector="#div1"time=5000그 HTML 태그를 찾습니다 id="div1"마다 5000 밀리 초.


답변

DOM에 새 요소가 추가 될 때마다 발생하는 이벤트를 청취 DOMNodeInserted하거나 들을 수 있습니다 DOMSubtreeModified.

새 요소가 생성되는시기를 감지하는 LiveQuery jQuery 플러그인 도 있습니다 .

$("#future_element").livequery(function(){
    //element created
});

답변

이 접근법을 사용하여 요소가 나타날 때까지 기다렸다가 그 후에 다른 기능을 실행할 수 있습니다.

doTheRestOfTheStuff(parameters)ID the_Element_ID가 있는 요소가 나타나거나로드가 완료된 후에 만 함수를 호출해야 한다고 가정 해 보겠습니다 .

var existCondition = setInterval(function() {
 if ($('#the_Element_ID').length) {
    console.log("Exists!");
    clearInterval(existCondition);
    doTheRestOfTheStuff(parameters);
 }
}, 100); // check every 100ms

답변

넌 할 수있어

$('#yourelement').ready(function() {

});

이것은 서버에서 요청할 때 요소가 DOM에 존재하는 경우에만 작동합니다. 요소가 JavaScript를 통해 동적으로 추가되는 경우 작동하지 않으며 다른 답변을 봐야 할 수도 있습니다.


답변

나는 여전히 쉽고 읽기 쉬운 작업 예제와 함께 여기에 어떤 대답도 없다고 생각합니다. MutationObserver interface 를 사용 하여 다음과 같이 DOM 변경을 감지하십시오.

var observer = new MutationObserver(function(mutations) {
    if ($("p").length) {
        console.log("Exist, lets do something");
        observer.disconnect();
        //We can disconnect observer once the element exist if we dont want observe more changes in the DOM
    }
});

// Start observing
observer.observe(document.body, { //document.body is node target to observe
    childList: true, //This is a must have for the observer with subtree
    subtree: true //Set to true if changes must also be observed in descendants.
});

$(document).ready(function() {
    $("button").on("click", function() {
        $("p").remove();
        setTimeout(function() {
            $("#newContent").append("<p>New element</p>");
        }, 2000);
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button>New content</button>
<div id="newContent"></div>

참고 : 자세한 정보를 원하면 스페인어 Mozilla 문서 MutationObserver가 더 자세합니다.