Tag Archives: Unobtrusive JavaScript

JavaScript optimization. Lazy loading.

Javascript files are too big!

Yes that’s the reality and when they become more and more bigger the web pages becomes to be irresponsible. The bitter reality is that you load any functionality that slows down the first user impression, but is needed only when you click on a button and so on. That’s a problem because you can load only that chunks you need in the beginning and than after a few seconds to load everything else. Some web applications have more than 100K of javascript which become really bad.

Separate logic

What you can do is to separate the logic into one or more files. Even when the user thinks everything is on the page and he can interact with the application and than to start to load the rest of the functionality.

That’s a pretty good technique. Nobody can start interacting on the 5th second of the load process. Usually the user looks at the interface starts to explore the app and after approximately the 10th second he start interacting with the page.

Lazy loading

There are various techniques of loading JavaScript on demand. So I wont cover it, but that pattern of loading it latter when needed is really powerful.

Manage JavaScript and CSS includes within Zend Framework application

How to include JavaScript and CSS files?

In Zend Framework there is a very elegant way to include CSS and JavaScript. Because in one single view of any action you cannot include a JavaScript or CSS because they wont be executed from the browser, you can simply use a helper.

You can see the original source of how that’s done here. And in breve you can include a JS file like so:

<? $this->headScript()->appendFile('/media/js/global.js') ?>

but where the problem is?

As a very good PHP point of view, there is really that way to include JS into the application. But a PHP point of view is not a JavaScript point of view so this solution is not the best one.

As almost everybody knows JavaScript blocks other content until it’s loaded and executed from the server and nowadays the most popular way to include JS is just before the closing <body> tag.

That’s why the ZF solution is not optimal. What we actually need as both PHP and JavaScript developers is a most robust solution!