The question is regarding the http://labjs.com – an awesome library for non-blocking JavaScript loading and dependencies managing.
I've read the docs, but I must be too tired or something – I couldn't find anything regarding DOM ready event. Are the scripts executed after the DOM's ready or not?
Perhaps if I do:
$LAB.script('my-library.js').wait(function(){
// interacting with DOM
});
Will it be safe? Or should I use some kind of $(function() {})
etc.?
Any script loader, by default, acts to unblock script loading from the page's DOM-ready and onload events, at least by intent/definition.
So, the straightforward answer is, NO, LABjs will not block script execution until DOM-ready. Some scripts loaded by LABjs may run before DOM-ready, while others may run after DOM-ready.
If you truly have cases where your code needs to wait for the DOM, you should use a framework like jQuery and use its built-in DOM-ready wrapper $(document).ready(...)
to make that logic DOM-ready-safe.
However, there are many cases where people think they need to wait for DOM-ready, when they really don't:
Most people conflate DOM-ready with "all scripts are done loading". If you are simply waiting for DOM-ready because you need to ensure that all your scripts have loaded, this is a mistaken and incorrect assumption to be making. Instead, use the facility of your script loader to determine when all scripts are loaded, and run them at the appropriate time, regardless of the DOM loading. With LABjs, this is as simple as having all your scripts in a single $LAB chain, and having a final .wait()
at the end of the chain -- you can be assured that your code in that .wait()
callback will not run until all the scripts have loaded and run.
Most people think they need to wait for DOM-ready to do things like attaching event handlers, or firing off Ajax requests. This is also an incorrect assumption. If your code simply queries the DOM for elements to attach event handlers to, or if you are doing nothing with the DOM at all, but are instead making Ajax calls, don't wrap your logic in a DOM-ready wrapper.
On the flip side, many people assume that if your code runs at the end of the body tag, then you don't need to wait for DOM-ready. Wrong. DOM-ready is DOM-ready, regardless where your code is specified.
In general, the only time your code really needs to be wrapped in a DOM-ready wrapper is if it is going to modify the DOM. Otherwise, don't wait for DOM-ready to run your code. Be smart about what is wrapped and what isn't.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With