Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery each() complete callback function

I'm trying to scan all stylesheets within DOM using following each() function

$("link").each(function(){
    $.get($(this).attr('href'), function() {
        // Some Code...
    });
});

This code works fine but I want to get callback to know that All Stylsheets have been scanned & Run another function thereafter. Is it possible to achieve this ?

like image 566
MANnDAaR Avatar asked Mar 17 '26 01:03

MANnDAaR


2 Answers

Create an array of $.Deferred objects:

var jqXHRs = $("link").map(function() {
  return $.get($(this).attr('href'), function () {
    // Some code...
  });
});

And then pass them to .when() and use the done() callback:

$.when.apply(null, jqXHRs.get()).done(
  function() {
    // All done
  }
);
like image 144
João Silva Avatar answered Mar 18 '26 16:03

João Silva


Why are you loading each stylesheet a second time (they already loaded in your page once) over AJAX when you could just interrogate them via the document.styleSheets API?

for (var i in document.styleSheets) {
    /* code here involving cssText or whatever */
}

Since this approach would constitute a synchronous operation, you wouldn't need a callback - you would just put your 'callback' code right after the loop.

like image 26
Mitya Avatar answered Mar 18 '26 16:03

Mitya



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!