CloudFlare describes Rocket Loader like this...
Rocket Loader is a general-purpose asynchronous JavaScript loader
coupled with a lightweight virtual browser which can safely run any
JavaScript code after window.onload.
Rocket Loader does a bunch of things:
- It ensures that all the scripts on your page will not block the content of your page from loading;
- Loads all the scripts on your page, including third party scripts, asynchronously;
- Bundles all the script requests into a single request over which multiple responses can be streamed;
- Uses LocalStorage on most browsers and nearly all smart phones to more intelligently store scripts so they aren't refetched unless
necessary.
So that's pretty cool, but how does it achieve it?
From what I've read and discovered from running CloudFlare + Rocket Loader on my own site, it works roughly like this...
When a HTML page is requested from a CloudFlare server, after loading it from the origin web host, it rewrites all script tags into <script type="
text/rocketscript
">
Browsers naturally ignore the script tags as they don't understand the format "text/rocketscript"
CloudFlare also injects an additional cloudflare.min.js
script into the page which performs the magic (see formatted version here). This is the only script initially loaded by the browser (asynchronously).
This script parses the page for any scripts with the type "text/rocketscript".
It then checks if any of these scripts already exist in the browser's local storage. If not, it then makes an AJAX request for them (combined in logical bundles) from the CloudFlare CDN. I'm not quite sure how it works out how to group the scripts together.
The CDN servers gather the scripts (which may come from several different servers: Google, Twitter, Facebook, other CDNs etc.), either from their cache, or from the origin servers, and then combine, minify and GZIP them before sending them back to the browser.
This virtual browser thing that they refer to must simply be some JavaScript that then runs each of these scripts in the right order, doing such things as:
- Catching all calls to
document.write()
and injecting that content into the correct location on the page. (Possibly by overwriting the browser's write()
function with a custom one?)
- Retriggering events such as DOMContentLoaded and load.
I'm actually quite shocked that it works (although perhaps it doesn't always). But under normal circumstances, I don't think developers need to do anything special to make their JavaScript compatible.
This is a community wiki, so please edit and add any additional detail that is missing.