jQuery.ready() equivalent event listener on elements?

后端 未结 3 1959
不思量自难忘°
不思量自难忘° 2020-11-30 10:03

I am using jQuery JavaScript library. I like the event listener ready on $(document) that fires when the DOM is set up.

( Pretty similar

相关标签:
3条回答
  • 2020-11-30 10:25

    There is no event fired when an arbitrary DOM element such as a <div> becomes ready. Images have their own load event to tell you when the image data has been loaded and has been rendered and a few other special types of elements have an event. But, regular DOM elements do not have such an event.

    If you want javascript code to be executed as soon as an arbitrary DOM element is ready, the only way to do that is to place a function call in an inline script right after that DOM element. At that point that DOM element will be ready, but the rest of the DOM afterwards may not yet be ready. Otherwise, the script can be placed at the end of the document or the script can be fired when the whole document is ready.

    Here are the existing load events expressed in jQuery form (these can all be done in plain JS too):

    // when a particular image has finished loading the image data
    $("#myImage").load(fn);
    
    // when all elements in the document are loaded and ready for manipulation
    $(document).ready(fn);
    
    // when the DOM and all dynamically loaded resources such as images are ready
    $(window).load(fn);
    

    In jQuery, you can also dynamically load content and be notified when that content has been loaded using the .load() method like this:

    $( "#result" ).load( "ajax/test.html", function() {
      alert( "Load was performed." );
    });
    

    Internally, this just does an ajax call to fetch the data and then calls the callback after the data has been retrieved by ajax and then inserted into the document. It isn't a native event.


    If you have some code that is dynamically loading elements in to the DOM and you want to know when those DOM elements are present, then the best way to know when they are ready is to have the code that adds them to the DOM create some sort of event to tell you when it's ready. This prevents battery wasting polling efforts trying to find out if the element is now in the DOM.

    It is also possible to use the DOM MutationObserver to see when specific types of changes have been made to the DOM.

    0 讨论(0)
  • 2020-11-30 10:36

    All elements (including div and img) are ready as soon as DOMReady fires - that's what it means.

    However, you can use the load() event to run some code when an img tag has fully loaded the image in it's src attribute:

    $('img').load(function() {
       console.log('image loaded');
    });
    
    0 讨论(0)
  • 2020-11-30 10:42

    jQuery don't have it, but we can create our own onDomElementIsReady, Tools: jQuery, ES6, Promise and Interval (I'm lazy, but you can get the idea)

    We will wait until the element existed on the DOM and as soon is available we will resolve the promise result.

      const onDomElementIsReady = (elementToWatch)=> {
        //create promise
        return new Promise((res, rej)=> {
          let idInterval = setInterval(()=> {
            //keep waiting until the element exist
            if($(elementToWatch).length > 0) {
              clearInterval(idInterval); //remove the interval
              res($(elementToWatch)); //resolve the promise             
            }
          },100);
        });
      };
    
    
    //how to use it?
    onDomElementIsReady(".myElement").then(element => { 
                              //use jQuery element
                       });
    

    NOTE: To improve this we should add a timer that reject the promise if the DOM element never exists.

    0 讨论(0)
提交回复
热议问题