Twitter this

Powered by MariaDB Powered by nginx ...

When document.ready does not work

document.ready comes short sometimes

Sometimes document.ready isn't enough. Or better, isn't what you want. Neither is window.onload stuff. You need something that has patience. In my quest for great stuff I came across a page - got the code, lost the bookmark - If you happen to recognise you're code here, let me know your contact details so I can send my thanks your way and put credits where due on the page here!

I think jquery lacks this kind of function, after reading the info that described the different pro's and con's of the methods used in ext.js or jquery and other approaches to declare it's ready to load something up (in 97 percent of the times we wait for the DOM). I decided to go with the auther and use another method that proved the best to have somthing wait just a tad longer to start loading than document.ready in jquery does.

So I'm dealing with the other 3%. I need to wait for a set of asynch AJAX calls that return JSON objects back, these were called in a init function, and 2 other functions that also contain ajax calls to provide content. The setup function needs to run first, it sets stuff up in the DOM that the others will manipulate.

Hence I found this little gem that works awesome. I have this in a file called onAvailable.js that you need to make sure to load this at the earliest. Usage like this:

onAvailable.js

1
2
3
4
  onAvailable('agendahead', function(){
   // setTimeout("loadAlarms();", 3000);
getmonthinfo();
});

So I needed a function that does this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
var stack = [],
    interval,
    loaded; // has window.onload fired?

function doPoll() {
  var notFound = [];
  for (var i=0; i<stack.length; i++) {
    if (document.getElementById(stack[i].id)) {
      stack[i].callback();
    } else {
      notFound.push(stack[i]);
    }
  }
  stack = notFound;
  if (notFound.length < 1 || loaded) {
    stopPolling();
  }
}

function startPolling() {
  if (interval) {return;}
  interval = setInterval(doPoll, 10);
}

function stopPolling() {
  if (!interval) {return;}
  clearInterval(interval);
  interval = null;
}

function onAvailable(id, callback) {
  stack.push({id:id, callback:callback});
  startPolling();
}

window.onload = function() {
  loaded = true;
  doPoll();
};

I've been playing with the idea of converting this to a Jquery plugin, guess it wouldn't be that hard to do so given the amount of code. I hope this was also interesting enough to read. This just sits and wait until that certain div block is there and then fires.

Comments are closed.

recruitment
recruitment
recruitment
recruitment