简体   繁体   中英

How to execute a function in javascript after an html element is loaded via AJAX without jQuery?

I need to execute a given javascript function after a part of the page is loaded via AJAX. I have no control over how the page loads so trigerring an event from the page is not an option, I suppose I'll need to check the body for the element I need and execute after this element is exists.

I saw that I could do this using jQuery ".on" method, but my jQuery version is from before this feature was introduced so I can't use it. What's the best way to do this using no third-party libraries?

Here's an example using jQuery:

//bind to the body a "load" handler for elements that have class names of "hello"
$('body').on('load','.hello',function(){
  alert("Hello is fully loaded, proceed with your program logic");
})

PS: related question that I've read before posting this one. How to bind a function to Element loaded via Ajax

You can create a function to call when the elements are loaded, and another function to check if they are loaded at an interval. Then attach the load checking function to the body's onload attribute. For example:

<body onload="checkLoaded()">

<script type="text/javascript">
    var afterLoaded = function() {
        // code to execute once elements are in place
        console.log("Elements loaded.");
    };

    var checkLoaded = function() {
        var interval = setInterval(function() {
            if(document.getElementsByClassName("hello").length) {
                clearInterval(interval);
                afterLoaded();
            }
        }, 1000);
    };
</script>

Plunker

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM