admin管理员组

文章数量:1415120

Since ajax is used widely today, many page contents are loaded asynchronously. Is there any way to know something is loaded after all DOMs are loaded? For example, whole page is loaded, but some images are created/loaded by new image(), how can I know these kinds of change happened in the web page by Javascript? Any event could be useful?

Since ajax is used widely today, many page contents are loaded asynchronously. Is there any way to know something is loaded after all DOMs are loaded? For example, whole page is loaded, but some images are created/loaded by new image(), how can I know these kinds of change happened in the web page by Javascript? Any event could be useful?

Share Improve this question edited Aug 20, 2020 at 11:23 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked May 5, 2011 at 5:34 icespaceicespace 9511 gold badge10 silver badges17 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 5

The mutation events as already mentioned should do the trick. If using jQuery, you can do something like this with the 'DOMSubtreeModified' mutation event:

$(document).ready(function () {
    $('body').bind('DOMSubtreeModified', 'test', function () {
        alert('something changed');
    });

    $('#some-button').click(function () {
        $('body').append('<h4>added content</h4>');
    });
});

Any content changes will display the alert box. In that example, when a button with id "some-button" is clicked, content is added to the body and the alert is shown. The mutation events offer some more specific type of events, the one I have shown is probably the most general.

There are some mutation events: http://www.w3/TR/2000/REC-DOM-Level-2-Events-20001113/events.html#Events-MutationEvent

onsubtreemodified
onnodeinserted
onnoderemoved
etc.
Look at here: https://developer.mozilla/en/DOM_Events

Following is a code piece which may help:-

<script>
    var img = new Image();
    img.src = "http://static.yourwebsite./filename.ext";
    img.onreadystatechange = function(){
        if((img.readyState == "plete") || (img.readyState == 4)) {
            alert("Image loaded dynamically!");
        }
    };
</script>

You must change the image source. The event onreadystatechange will help you to find out if the image has been loaded or not. readyState must be plete or 4 as sent by AJAX if I'm not mistaken when the page is fetched.

OR YOU MAY GO WITH

<script>
    var img = new Image();
    img.src = "http://static.yourwebsite./filename.ext";
    img.onload = function(){
        alert("Image loaded dynamically!");
    };
</script>

CREDIT FOR THE ABOVE CODE: http://www.techrepublic./article/preloading-and-the-javascript-image-object/5214317

In this code piece, we use onload event to trigger the image load

Hope this helps. Mark this as the answer if this helps! :D

Cheers

本文标签: javascriptListen page content updatedStack Overflow