Use jquery before the DOM is ready
Hi all,
yesterday I was chatting on the IRC jquery channel and someone asked how
to use jQuery before the DOM was ready.
Sometime the DOM ready event is a bit late, causing flicker on the page
or unresponsive (not still binded) links.
So I wrote a proof of concept to implement:
- $.elementAvailable(selector,callback,once)
- $.elementComplete(selector,callback,once)
inspiring my code to YUI, setting a polling interval to search in the
not yet complete DOM.
$.elementAvailable calls the callback as soon as the selector finds
something (even if the selector content is not complete)
$.elementComplete calls the callback as soon as any of the selector
elements are complete (all their content has been loaded)
This is useful if you want to target the last child of an element.
The "once" parameter gives a hint about how many matches will be found.
When using an ID selector,
setting once=true makes the plugin to stop searching once a successful
match has been found.
The code is at
http://www.fbtools.com/jquery_test/jBeforeReady/jBeforeReady.js , I've
putted a short doc inside.
I've setted up an ugly demo too
http://www.fbtools.com/jquery_test/jBeforeReady/index.html
The page is quite heavy (about 250Kb) and is made of a clickable link at
the beginning and two <ul>, the first being short,
the second very long.
You can click on the link very early in the loading process and see that
jQuery add text in an empty <div>,
see when the two <ul> are completely loaded and when the DOM is complete.
It seems to work on FF,Opera,Safari and IE.
The script is very light, less than 40 lines of code without white lines
and comments.
You can use http://www.dallaway.com/sloppy/ (it's a java software) to
simulate a slow connection and see how this plugin helps.
Do you think this feature can be interesting for the core?
Renato