简体   繁体   中英

Waiting for all DOM manipulations to finish with jQuery?

I have a slight dilemma on exactly how to accomplish something. I am coding a portfolio which has a masonry layout using a plugin called isotope. It's basically pinterest style layout. I will also have filters that will automatically grab the right content from the database and insert it with a mustache template. Now the problem I have is how do I wait for all the dom insertion to finish before I run the isotopes relay-out function. Because if I run it too soon the elements won't get positioned properly. I dont want to do a setTimeout() function because Im not sure how long the database request will take and I dont want to make the user wait too long.

Any suggestions?

Check out jQuery Deferred.done()

Here is the example from the site:

<!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>

 <button>Go</button>
 <p>Ready...</p>

<script>
/* 3 functions to call when the Deferred object is resolved */
function fn1() {
  $("p").append(" 1 ");
}
function fn2() {
  $("p").append(" 2 ");
}
function fn3(n) {
  $("p").append(n + " 3 " + n);
}

/* create a deferred object */
var dfd = $.Deferred();

/* add handlers to be called when dfd is resolved */
dfd
/* .done() can take any number of functions or arrays of functions */
.done( [fn1, fn2], fn3, [fn2, fn1] )
/* we can chain done methods, too */
.done(function(n) {
  $("p").append(n + " we're done.");
});

/* resolve the Deferred object when the button is clicked */
$("button").bind("click", function() {
  dfd.resolve("and");
});
</script>

</body>
</html>  

Also there is a demo on the site as well.

You can call relayOut method in the callback of insert function.

$('#container').isotope( 'insert', /*items*/ ,function(){
  $('#container').isotope( 'reLayout', callback );
} );

Or you can give all method as chain

$('#container').isotope( 'insert', /*items*/).isotope( 'reLayout', callback );

If you are calling your content using ajax you can call your relayOut on the last line of success callback of jquery ajax. So every DOM manipulation is done before you call relayOut method.

refer to http://isotope.metafizzy.co/docs/methods.html for callback and chaining method of isotope plugin. for jquery ajax go through http://api.jquery.com/jQuery.ajax/

您当前是否在$(document).ready(function()内部运行该函数?也许您可以在$(window).load(function()内部尝试该函数。

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