UpTheCreek
UpTheCreek

Reputation: 32391

window.onload equivalent after modifying the DOM?

When a page first loads we can use window.onload to make sure that all resources have loaded before we do something.

My question is, if we modify the DOM (e.g. inserting some html based on an ajax request), is there any event that will fire when the document is in the 'loaded' state again? (e.g. when the html inserted contains multiple images).

(Solution with jQuery would be fine).

Upvotes: 5

Views: 1314

Answers (3)

bart s
bart s

Reputation: 5100

I would say YES (I do not know if this is supported by all browsers. I use it in safari and chrome)

Testcase you can find here : http://maakmenietgek.nl/testcases/domready/ Please note that I cannot get it work in a fiddle, that's why a standalone testcase

The index.html looks like this

<!DOCTYPE html>
<head>
  <title>Testcase</title>
  <script src="jquery-1.8.2.js" type="text/javascript" charset="utf-8"></script>
  <script type="text/javascript">
    $(document).ready(function() {
      $('#clickme').click(function() {
        $.get('ajaxdata.html', function(data) {
            $('#addhere').html(data);
        });
      });
    })
  </script>
</head>
<body>
  <p id="clickme">clickme</p>
  <div id="addhere">
  </div>
</body>
</html>

The data loaded with the $.get call looks like this

<p>added data</p>
<script type="text/javascript">
    $(document).ready(function() {
        alert('added data');
    });
</script>

The alert shows after the html has been added to the DOM

Upvotes: 0

Nadav Ben-Gal
Nadav Ben-Gal

Reputation: 549

The short answer: NO.

The long answer: if you know what you are looking for you can use mutation observers (https://developer.mozilla.org/en-US/docs/DOM/MutationObserver). it is only support in new browser, and in some version of chrome it has memory leaks when used with closures.

BTW, document.ready doesn't tell you if all (or any..) of the resources were loaded. it only tell you well, that the dom is ready (that is the load function, which will only fire after all resources (well, any resources that isn't requested using a javascript) were downloaded).

Upvotes: 2

Dipesh Parmar
Dipesh Parmar

Reputation: 27364

You can use .done().

Description: Add handlers to be called when the Deferred object is resolved.

Also there is jQuery plugin See Here

Upvotes: 0

Related Questions