My JavaScript book is out! Don't miss the opportunity to upgrade your beginner or average dev skills.

Sunday, August 14, 2011

Once Again On Script Loaders

It's a long story I would like to summarize in few concrete points ...

Three Ways To Include A Script In Your Page

First of all, you may not need loaders at all.
Most likely you may need an easy to go and cross platform build process, and JSBuilder is only one of them.

The Most Common Practice

This way lets users download and visualize content first but it lets developers start the JS logic ASAP as well without mandatory need to set DOMContentLoaded or onload event.

<!doctype html>
<head>
<!-- head content here -->
</head>
<body>
<!-- body content here -->
<script src="app.minzipped.js">/* app here */</script>
</body>
</html>


The "May Be Better" Practice

I keep saying that a web application that does not work without JavaScript should never be accessed by a user. As example, if a form won't submit without JavaScript what's the point to show it before it can possibly work? If your page strongly depends on JavaScript don't be afraid to let the user wait slightly more before the layout is visualized. The alternative is a broken experience as welcome. Accordingly, use the DOMContentLoaded listener over this ordered layout:

<!doctype html>
<head>
<!-- head content here -->
<script src="app.minzipped.js">/* app here */</script>
</head>
<body>
<!-- body content here -->
</body>
</html>

If you don't trust the DOMContentLoaded listener you can combine both layouts:

<!doctype html>
<head>
<!-- head content here -->
<script src="app.minzipped.js">/* app here */</script>
</head>
<body>
<!-- body content here -->
<script>initApp();</script>
</body>
</html>


The Optional "defer" Attribute

We can eventually try to avoid the blocking problem using a defer attribute. However, this attribute is not yet widely supported cross browser and the result may be unexpected.
Since this attribute is basically telling the browser to do not block downloads, in the very next future it could be specified both on head script or before the end of the body.
Everything I have said about possible broken UX is still valid so ... use carefully.

The Loading Practice

Classic example is twitter on mobile browsers and any native application with a loading bootstrap screen. Also Flash based websites use this technique since ages and users are used to it.
If the amount of javascript plus CSS and assets is massive, both precedent techniques will fail.
The first one will fail because the user doesn't know when the script will be loaded plus it's blocking so the page won't respond. Bye bye user.
The second approach will result into a too long waiting time over a blank page ... bye bye user.
This loading approach will entertain the user for a little while, it will be lightweight, fast to visualize, and it can hold the user up to "5 seconds" with cleared cache ( and hopefully much less next time with cache but if more we should really think to split the logic and lazy load as much as possible ).

<!doctype html>
<head>
<!-- head content here -->
<!-- most basic CSS -->
</head>
<body>
<!-- most basic content -->
<!-- "animated gif" or loader spin -->
<script src="bigstuff.minzipped.js">/* code */</script>
<!-- optional BIG CSS -->
</body>
</html>


This page should be as attractive as possible and no interaction that depends on JavaScript should be shown.

Why Scripts Loaders

Because an articulated website may have articulated logic split in different files.
The main page may rely into jQuery, commonLogic, mainPageLogic.
Any sub section in the site may depend on jQuery, commonLogic, subSectionLogic, adHocSectionLogic, etc.
The build approach will fail big time here because every page will contain a different script to download in all its variants.
Moreover, thanks to CDN some library can be cached cross domain, including as example jQuery from that CDN.
In this scenario a script loader is the best solution:

$LAB
.script("http://commoncdn.com/jquery")
.script("commonLogic.js")
.wait()
.script("subSectionLogic.js")
.wait()
.script("adHocSectionLogic.js")
.wait(function () {
// eventually ready to go
// in this section
})
;

Above example is based on LAB.js, a widely adopted library I have actually indirectly contributed as well solving one conflict with jQuery.ready() method.

script() and wait()

LAB.js has been created with performances in mind where every script will be pre downloaded as soon as it's defined in the chained logic.
The wait() method is a sort of "JS interpretation break point" and it's really useful when a script depends on another script.
Let's say commonLogic is just a set of functions while subSectionLogic starts with a jQuery.ready(function () { ... }) call, LAB.js will ensure that latter script won't be executed until jQuery is ready ... got it?
LAB.js size once minzipped is about 2.1Kb and the best way to use it is to include LAB.js as very first script in whatever page.
AFAIK LAB.js is not yet hosted in any major CDN but I do believe that will happen soon.

Preload Compatibility

LAB.js uses different techniques to ensure both pre downloads and wait() behavior. Unfortunately some adopted fallback looks inevitably weak to me.
As example, I am not a big fun of "empty setTimeouts" solutions since these are used as workaround over unpredictable behaviors.
One of these behaviors is the readyState script property that on "complete" state may have or may have not already interpreted the script on "onreadystatechange" notification.
If we have a really slow power machine, as my netbook is, the timeout used to decide that the script has been already parsed may not be enough.
I don't want to bother you with details, I simply would like you to understand why I came out with an alternative loader.
Before I reach that point I wanna show an alternative technique to get rid of wait() calls.

Update
It looks like few setTimeout calls will be removed soon plus apparently the setTimeout I pointed out has nothing to do with wait: my bad.
In any case I don't fancy empty timers plus LAB.js logic is focused on cross browser parallel pre-downloads and for this reason a bit more bigger in size than all I needed for my purpose.

Avoiding wait() Calls

JavaScript let us successfully download and parse scripts like this without problems:

function initApplication() {
jQuery.ready(function () {
// whatever we need to do
});
}

Please note that no error will be thrown even if jQuery has not been loaded yet.
The only way to have an error is to invoke the function initApplication() without jQuery library in the global scope.
In few words, we are not in Java or C# world where the compiler will argue if some namespace is accessed in any defined method and not present/included as dependency before ... we are in JavaScript, much cooler, isn't it? ;)
Accordingly, if the current page initialization is wrapped in a single function we could simply use a single wait call at the end.

$LAB // no direct jQuery calls in the global scope
.script("http://commoncdn.com/jquery")
.script("commonLogic.js")
.script("subSectionLogic.js")
.script("adHocSectionLogic.js")
.wait(function () {
initApplication();
})
;

The potential wait() problem I am worried about is still there but at least in a single exit point rater than distributed through the whole loading process ... still bear with me please.

The Namespace Problem


The generic init function can be part of a namespace as well. If we have namespaces the problem is different 'cause we cannot assign my.namespace.logic.init = function () {} before my.namespace object has been defined.
In this case we either create a global function for each namespace initialization/assignment or we impose a wait() call between every included namespace based file.

yal.js - Yet Another ( JavaScript ) Loader


Update
yal.js now on github


As written in yal.js landing page I have been dealing with JS loaders for a while.
This library created a sort of "little twitter war" between me and @getify where Kyle main arguments were "why another loader?" followed by "LAB.js has better performances".

Why yal.js

It's really a tiny script that took me 1 hour tests included plus 20 minutes of refactoring in order to implement a sort of "forced preload" alternative ( which kinda works but I personally don't like and neither does Kyle ).
yal.js is just an alternative to LAB.js and we all like alternatives, don't we?
The main focus of yal.js is being as small and as cross browser as possible using KISS and YAGNI principles.

No Empty Timers Essential Script Logic

yal.js is based on script "onload" event which behavior is already defined as standard and it's widely compatible.
If not usable in some older browser, the more reliable "loaded" state of readyState property is used instead. This state comes always after the "loading" or "complete" one.
I could not trigger any crash or problem wit this approach and together with next point no need to use unpredictable timers.

Simplified Wait Logic

In the basic version of the script any wait() call will block other scripts. These won't be pre downloaded until the previous call has been completed.
However, if we consider we may not even need wait calls:

yal // no direct jQuery calls in the global scope
.script("http://commoncdn.com/jquery")
.script("commonLogic.js")
.script("subSectionLogic.js")
.script("adHocSectionLogic.js")
.wait(function () {
initApplication();
})
;

yal will perform parallel downloads same way LAB.js does and, being yal just 1.5Kb smaller, performances will be slightly better on yal rather than LAB.js
Also for my bad experience with "complete" state, I feel a bit more secure with the fact that when wait() is invoked in yal.js, everything before has been surely already interpreted and executed ( but please prove me wrong if you want with a concrete example I can test online, thanks )

Just What I Need

For my random and sporadic personal projects yal.js fits all my requirements. I do not use the forced parallel downloads and I don't care. I have asked Kyle to be able to grab a subset of LAB.js getting rid of all extra features surely useful for all possible cases out there but totally unnecessary for mine. Unfortunately that would not have happened any soon so I created the simplest solution for all I personally needed.

As Summary


I am actually sorry Kyle took my little loader as a "non sense waste of time" and if that's what you think as well or if you need much more from a loader, feel free to ignore it and go happily with LAB.js
Also I am not excluding that the day LAB.js will be in any major CDN I will start using it since at that point there won't be any overhead at all and cross domain.

Finally, in this post I have tried to summarize different techniques and approaches to solve a very common problem in this RIA era, hope you appreciated.

9 comments:

Ignat Ignatov said...

Have you tried HeadJS? I used in few projects and I can highly recommend it. I would be interested how yal.js compares to it.

Benvie said...

How about cheating by exploiting psychology? If we're talking about a user loading some data on a page, there's a lot of things outside the context of "load really fast" that can serve.

I submitted an example here a while back: http://littlebigdetails.com/post/6417364960/amazon-when-you-click-next-page-while-viewing

Essentially: Amazon hides the last 3 results for a query until you go to the next page. It then instantly shows those 3 results while loading the next page. No magic technology involved, it literally just hides some stuff to show you ONLY when you're waiting for new data. 100% human psychology.

Why is this not commonoplace?

Andrea Giammarchi said...

@Ignat\ Ignatov never tried HeadJS but it's overloaded of stuff I personally don't really need. yal.js does only the script loading part which is what I may need :)

@Benvie there are "infinite" things to consider and this post is about landing page and common distributed subset of functionalities websites.
The best way in between two pages is extremely hard to tell since it's totally context oriented.
Landing/home pages? These are almost the same in RIA ;)

Ignat Ignatov said...

@Andrea Giammarchi - actually HeadJS has a loader-only version - it's only around 3KB. It's not so obvious although it's in the download section (the file is called head.load.min.js). Also you may be interested to submit your loader here: http://goo.gl/nKD1K - a comparison of all JavaScript loaders.

Andrea Giammarchi said...

3Kb minzipped or just minified? In first case I would go LAB.js, in second case I am in less than 700 bytes not gzipped ;)

I'll check the list

Andrea Giammarchi said...

added yal.js at the end of the list

Christopher said...

I was reading over the source code of yal.js... not "all the way through" tho. @Andrea remains my favorite JS hacker.

I'm sure this may be a naive question, but I'll ask it anyway: Why do you pass the global object as an argument to the closure? I know you don't want to reference "window" directly, but why not just use "this" like so:

var yal = function(){ ... }.call(this);

just a byte-saver I guess?

Andrea Giammarchi said...

@Christopher Minifiers cannot/dont minify "this" references so:

var $=function(){return this}.call(this);

VS

var $=function(g){return g}(this);

Also the latter one let me redefine "window" on top of the function if necessary ( e.g. I am dealing with node.js where "this" refers to the module and not the global object )

As summary, nothing bad with your snippet but it's bigger and less easy to change for no concrete reasons, you know what I mean? :)

Anonymous said...

I really liked the article, and the very cool blog