복붙노트

[JQUERY] 요소가 존재 할 때까지 얼마나 기다려야합니까?

JQUERY

요소가 존재 할 때까지 얼마나 기다려야합니까?

해결법


  1. 1.DOMNodeInserted 때문에 성능 문제, 다른 DOM 돌연변이 이벤트와 함께 사용되지 않는 경우 - 권장되는 방법은 DOM을보기 위해 MutationObserver을 사용하는 것입니다. MutationObserver를 사용할 수 없을 때 당신이 DOMNodeInserted에 후퇴한다, 그래서 그것은 단지,하지만 새로운 브라우저에서 지원합니다.

    DOMNodeInserted 때문에 성능 문제, 다른 DOM 돌연변이 이벤트와 함께 사용되지 않는 경우 - 권장되는 방법은 DOM을보기 위해 MutationObserver을 사용하는 것입니다. MutationObserver를 사용할 수 없을 때 당신이 DOMNodeInserted에 후퇴한다, 그래서 그것은 단지,하지만 새로운 브라우저에서 지원합니다.

    let observer = new MutationObserver((mutations) => {
      mutations.forEach((mutation) => {
        if (!mutation.addedNodes) return
    
        for (let i = 0; i < mutation.addedNodes.length; i++) {
          // do things to your newly added nodes here
          let node = mutation.addedNodes[i]
        }
      })
    })
    
    observer.observe(document.body, {
        childList: true
      , subtree: true
      , attributes: false
      , characterData: false
    })
    
    // stop watching using:
    observer.disconnect()
    

  2. 2.내가 나서서 그것을 위해 플러그인을 쓴, 그래서 나는이 같은 문제가되었다.

    내가 나서서 그것을 위해 플러그인을 쓴, 그래서 나는이 같은 문제가되었다.

    $ (Kaitīpako) .waitUntilExists (기능);

    암호:

    ;(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));
    

  3. 3.다음 요소의 표시를 대기 코어 자바 스크립트 함수이다.

    다음 요소의 표시를 대기 코어 자바 스크립트 함수이다.

    매개 변수 :

    예를 들어, id가 = "div1"모든 5000 밀리 초 HTML 태그를 찾습니다 = 5000 선택 = "#의 div1"와 시간을 설정.


  4. 4.나는 그 후 다른 기능을 실행할 수 있도록 표시하는 요소에 대해 대기에이 방법을 사용했다.

    나는 그 후 다른 기능을 실행할 수 있도록 표시하는 요소에 대해 대기에이 방법을 사용했다.

    하자가, ID the_Element_ID를 가진 요소가 나타나거나 완성 된 로딩, 우리가 사용할 수 있습니다 후 doTheRestOfTheStuff (매개 변수) 함수는 호출해야한다고

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

  5. 5.새 요소가 DOM에 추가 될 때마다있는 화재 DOMNodeInserted 또는 DOMSubtreeModified 이벤트를 수신 할 수 있습니다.

    새 요소가 DOM에 추가 될 때마다있는 화재 DOMNodeInserted 또는 DOMSubtreeModified 이벤트를 수신 할 수 있습니다.

    새로운 요소가 생성 될 때 감지 할 LiveQuery jQuery 플러그인도 있습니다 :

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

  6. 6.넌 할 수있어

    넌 할 수있어

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

    서버에서 요청되는 때 요소가 DOM에 존재하는 경우에만 동작합니다주십시오 참고. 요소가 동적으로 자바 스크립트를 통해 추가되는 경우에는 작동하지 않습니다 그리고 당신은 다른 답변을 볼 필요가 있습니다.


  7. 7.나는 아직도 쉽게 읽을 작업 예제와 함께 어떤 답을 밤은 생각합니다. 사용 MutationObserver 인터페이스는이 같은 DOM의 변화를 감지 :

    나는 아직도 쉽게 읽을 작업 예제와 함께 어떤 답을 밤은 생각합니다. 사용 MutationObserver 인터페이스는이 같은 DOM의 변화를 감지 :

    var에 관찰자 = 새로운 MutationObserver (기능 (돌연변이) { 경우 ($ ( "P"). 길이) { CONSOLE.LOG는 ( "존재는, 뭔가를 할 수 있습니다"); observer.disconnect (); 우리는 DOM에 더 많은 변화를 관찰 싶지 않는 경우 // 우리는 요소가 존재 한 번 관찰자를 분리 할 수 ​​있습니다 } }); // 시작 관측 observer.observe (는 document.body는 {//document.body은 관찰 대상 노드 childList : 사실은, // 이것은이 하위 트리와 관찰자이 있어야합니다 하위 트리 : 변화도 자손에서 관찰해야하는 경우 true로 // true로 설정됩니다. }); $ (문서) .ready (함수 () { $ ( "버튼"). (함수를 "클릭"에 () { $ ( "P") 제거 ().; 에서는 setTimeout (함수 () { . $ ( "# newContent")를 APPEND ( "

    새로운 요소 "); }, 2000); }); }); <스크립트 SRC = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"> <버튼> 새로운 내용


  8. 8.단순히 당신이 원하는 선택을 추가합니다. 요소가 발견되면 당신은 콜백 기능에 액세스 할 수 있습니다.

    단순히 당신이 원하는 선택을 추가합니다. 요소가 발견되면 당신은 콜백 기능에 액세스 할 수 있습니다.

    const waitUntilElementExists = (selector, callback) => {
    const el = document.querySelector(selector);
    
    if (el){
        return callback(el);
    }
    
    setTimeout(() => waitUntilElementExists(selector, callback), 500);
    }
    
    waitUntilElementExists('.wait-for-me', (el) => console.log(el));
    

  9. 9.jQuery를 I의 한을 사용하여 간단한 방법이 잘 작동하는 것으로 확인 :

    jQuery를 I의 한을 사용하여 간단한 방법이 잘 작동하는 것으로 확인 :

      // Wait for element to exist.
      function elementLoaded(el, cb) {
        if ($(el).length) {
          // Element is now loaded.
          cb($(el));
        } else {
          // Repeat every 500ms.
          setTimeout(function() {
            elementLoaded(el, cb)
          }, 500);
        }
      };
    
      elementLoaded('.element-selector', function(el) {
        // Element is ready to use.
        el.click(function() {
          alert("You just clicked a dynamically inserted element");
        });
      });
    

    여기에서 우리는 단순히 때, 우리가 그것을 사용할 수있는 요소가로드 여부를 확인하기 위해 모든은 500ms를 확인합니다.

    이 동적 문서에 추가 된 요소로 클릭 핸들러를 추가 할 때 특히 유용합니다.


  10. 10.여기 MutationObserver 주위에 얇은 래퍼 역할을하는 기능입니다. 유일한 요구 사항은 브라우저 지원 MutationObserver이다; JQuery와에 대한 종속성이 없습니다. 작업의 예를 보려면 아래의 미리보기를 실행합니다.

    여기 MutationObserver 주위에 얇은 래퍼 역할을하는 기능입니다. 유일한 요구 사항은 브라우저 지원 MutationObserver이다; JQuery와에 대한 종속성이 없습니다. 작업의 예를 보려면 아래의 미리보기를 실행합니다.

    함수 waitForMutation (인 parentNode, isMatchFunc, handlerFunc, observeSubtree, disconnectAfterMatch) { VAR defaultIfUndefined 기능 (계산해에 defaultVal)을 {= 리턴 (대해서 typeof 발 === "정의되지 않은")? 에 defaultVal : 발; }; observeSubtree = defaultIfUndefined (observeSubtree 거짓); disconnectAfterMatch = defaultIfUndefined (disconnectAfterMatch 거짓); var에 관찰자 = 새로운 MutationObserver (기능 (돌연변이) { mutations.forEach (기능 (돌연변이) { 경우 (mutation.addedNodes) { 경우 (나는 <스팬 클래스 = 'foo는'> 외부 "); $ outerContent.append (newNode); }); $ ( "#의 addInner"). (함수를 "클릭"에 () { VAR newNode = $ ( "

    <스팬 클래스 = 'foo는'> 내부 "); $ innerContent.append (newNode); }); .content { 패딩 : 1em; 국경 : 고체 픽셀 두께의 블랙; 오버 플로우-Y : 자동; } #innerContent { 높이 : 100 픽셀; } #outerContent { 높이 : 200 픽셀; } #log { 글꼴 - 가족 : 택배; 폰트 크기 : 10pt로; } <스크립트 SRC = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">

    만들기 일부 돌연변이 <버튼 ID = "addOuter"> 외부 노드를 추가 <버튼 ID = "addInner가"> 내부 노드를 추가

    로그


  11. 11.어떻게 insertionQuery 라이브러리에 대한?

    어떻게 insertionQuery 라이브러리에 대한?

    insertionQuery는 요소가 생성 될 때 콜백을 실행하도록 지정된 선택기 (들)에 부착 된 CSS 애니메이션 콜백을 사용한다. 이 방법은 요소가 아니라 처음 생성 될 때마다 콜백을 실행 할 수 있습니다.

    GitHub의에서 :


  12. 12.이 약속에 사용되는 파티 libs와 또는 타이머 제 3를 사용하지 않는 사람들을위한 간단한 솔루션입니다.

    이 약속에 사용되는 파티 libs와 또는 타이머 제 3를 사용하지 않는 사람들을위한 간단한 솔루션입니다.

    나는 잠시 동안 내 프로젝트에서 그것을 사용하고있다

    function waitForElm(selector) {
        return new Promise(resolve => {
            if (document.querySelector(selector)) {
                return resolve(document.querySelector(selector));
            }
    
            const observer = new MutationObserver(mutations => {
                if (document.querySelector(selector)) {
                    resolve(document.querySelector(selector));
                    observer.disconnect();
                }
            });
    
            observer.observe(document.body, {
                childList: true,
                subtree: true
            });
        });
    }
    

    이 기능을 사용하려면 :

    waitForElm('.some-class').then(elm => console.log(elm.textContent));
    

    이나와 비동기 / await를

    const elm = await waitForElm('.some-classs')
    

  13. 13.여기에 바닐라 자바 ​​스크립트의 약속을 돌려주는 솔루션 (더 지저분한 콜백)입니다. 기본적으로는 200ms마다를 확인합니다.

    여기에 바닐라 자바 ​​스크립트의 약속을 돌려주는 솔루션 (더 지저분한 콜백)입니다. 기본적으로는 200ms마다를 확인합니다.

    function waitFor(selector) {
        return new Promise(function (res, rej) {
            waitForElementToDisplay(selector, 200);
            function waitForElementToDisplay(selector, time) {
                if (document.querySelector(selector) != null) {
                    res(document.querySelector(selector));
                }
                else {
                    setTimeout(function () {
                        waitForElementToDisplay(selector, time);
                    }, time);
                }
            }
        });
    }
    

  14. 14.여기에 당신은 아무것도를 기다릴 수있는 순수 자바 스크립트 기능입니다. 적은 CPU 리소스를 취할 이상 간격을 설정합니다.

    여기에 당신은 아무것도를 기다릴 수있는 순수 자바 스크립트 기능입니다. 적은 CPU 리소스를 취할 이상 간격을 설정합니다.

    /**
     * @brief Wait for something to be ready before triggering a timeout
     * @param {callback} isready Function which returns true when the thing we're waiting for has happened
     * @param {callback} success Function to call when the thing is ready
     * @param {callback} error Function to call if we time out before the event becomes ready
     * @param {int} count Number of times to retry the timeout (default 300 or 6s)
     * @param {int} interval Number of milliseconds to wait between attempts (default 20ms)
     */
    function waitUntil(isready, success, error, count, interval){
        if (count === undefined) {
            count = 300;
        }
        if (interval === undefined) {
            interval = 20;
        }
        if (isready()) {
            success();
            return;
        }
        // The call back isn't ready. We need to wait for it
        setTimeout(function(){
            if (!count) {
                // We have run out of retries
                if (error !== undefined) {
                    error();
                }
            } else {
                // Try again
                waitUntil(isready, success, error, count -1, interval);
            }
        }, interval);
    }
    

    jQuery를, 예를 들어,이 전화를 걸려면 같은 것을 사용 :

    waitUntil(function(){
        return $('#myelement').length > 0;
    }, function(){
        alert("myelement now exists");
    }, function(){
        alert("I'm bored. I give up.");
    });
    

  15. 15.해결책은 약속을 반환하고 타임 아웃 (호환 IE를 11 +) 사용할 수 있도록.

    해결책은 약속을 반환하고 타임 아웃 (호환 IE를 11 +) 사용할 수 있도록.

    하나의 요소에 대해 (요소를 입력하십시오) :

    "use strict";
    
    function waitUntilElementLoaded(selector) {
        var timeout = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
    
        var start = performance.now();
        var now = 0;
    
        return new Promise(function (resolve, reject) {
            var interval = setInterval(function () {
                var element = document.querySelector(selector);
    
                if (element instanceof Element) {
                    clearInterval(interval);
    
                    resolve();
                }
    
                now = performance.now();
    
                if (now - start >= timeout) {
                    reject("Could not find the element " + selector + " within " + timeout + " ms");
                }
            }, 100);
        });
    }
    

    여러 요소 (노드 목록 형)의 경우 :

    "use strict";
    
    function waitUntilElementsLoaded(selector) {
        var timeout = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
    
        var start = performance.now();
        var now = 0;
    
        return new Promise(function (resolve, reject) {
            var interval = setInterval(function () {
                var elements = document.querySelectorAll(selector);
    
                if (elements instanceof NodeList) {
                    clearInterval(interval);
    
                    resolve(elements);
                }
    
                now = performance.now();
    
                if (now - start >= timeout) {
                    reject("Could not find elements " + selector + " within " + timeout + " ms");
                }
            }, 100);
        });
    }
    

    예를 들면 :

    waitUntilElementLoaded('#message', 800).then(function(element) {
        // element found and available
    
        element.innerHTML = '...';
    }).catch(function() {
        // element not found within 800 milliseconds
    });
    
    waitUntilElementsLoaded('.message', 10000).then(function(elements) {
        for(const element of elements) {
            // ....
        }
    }).catch(function(error) {
        // elements not found withing 10 seconds
    });
    

    요소의 목록과 하나의 요소 모두를 위해 작동합니다.


  16. 16.MutationObserver를 사용하는 청소기 예 :

    MutationObserver를 사용하는 청소기 예 :

    new MutationObserver( mutation => {
        if (!mutation.addedNodes) return
        mutation.addedNodes.forEach( node => {
            // do stuff with node
        })
    })
    

  17. 17.당신이 잠시 동안 (타임 아웃) 후보고 중지하려면 다음 jQuery를 작동합니다. 그것은 10 초 후 시간이 초과됩니다. 내가 이름을 통해 입력을 선택하기 위해 필요하고 문제가 다른 솔루션의 일부를 구현을 가지고 있었기 때문에 순수 JS 대신이 코드를 사용하는 데 필요한.

    당신이 잠시 동안 (타임 아웃) 후보고 중지하려면 다음 jQuery를 작동합니다. 그것은 10 초 후 시간이 초과됩니다. 내가 이름을 통해 입력을 선택하기 위해 필요하고 문제가 다른 솔루션의 일부를 구현을 가지고 있었기 때문에 순수 JS 대신이 코드를 사용하는 데 필요한.

     // Wait for element to exist.
    
        function imageLoaded(el, cb,time) {
    
            if ($(el).length) {
                // Element is now loaded.
    
                cb($(el));
    
                var imageInput =  $('input[name=product\\[image_location\\]]');
                console.log(imageInput);
    
            } else if(time < 10000) {
                // Repeat every 500ms.
                setTimeout(function() {
                   time = time+500;
    
                    imageLoaded(el, cb, time)
                }, 500);
            }
        };
    
        var time = 500;
    
        imageLoaded('input[name=product\\[image_location\\]]', function(el) {
    
         //do stuff here 
    
         },time);
    

  18. 18.나는 보통 태그 관리자에이 코드 조각을 사용합니다 :

    나는 보통 태그 관리자에이 코드 조각을 사용합니다 :

    <script>
    (function exists() {
      if (!document.querySelector('<selector>')) {
        return setTimeout(exists);
      }
      // code when element exists
    })();  
    </script>
    

  19. 19.당신이 DOM 요소에 대한 비동기 DOM 변경 (초 시간 제한)이 기능 검사가 있다면, 그것을 기반으로 DOM과의 약속에 대한 무거운되지 않습니다 :)

    당신이 DOM 요소에 대한 비동기 DOM 변경 (초 시간 제한)이 기능 검사가 있다면, 그것을 기반으로 DOM과의 약속에 대한 무거운되지 않습니다 :)

    function getElement(selector, i = 5) {
      return new Promise(async (resolve, reject) => {
        if(i <= 0) return reject(`${selector} not found`);
        const elements = document.querySelectorAll(selector);
        if(elements.length) return resolve(elements);
        return setTimeout(async () => await getElement(selector, i-1), 1000);
      })
    }
    
    // Now call it with your selector
    
    try {
      element = await getElement('.woohoo');
    } catch(e) { // catch the e }
    
    //OR
    
    getElement('.woohoo', 5)
    .then(element => { // do somthing with the elements })
    .catch(e => { // catch the error });
    
  20. from https://stackoverflow.com/questions/5525071/how-to-wait-until-an-element-exists by cc-by-sa and MIT license