javascriptmagentohead.jslabjs

How to use a JavaScript loader like head.js or labjs in Magento


Off the bat Magento comes with more than half a dozen JavaScript libraries which do not help with the already cumbersome load times. Has anybody been able to successfully use a script loader like head.js or labjs with Magento so that they can load asynchronously? I have been trying but can't get it to work.

Seems as though the in-line scripts on the pages are firing before the libraries are loaded. I know that head.js has a function like head.ready to tell a script to execute , but there are so many in-line scripts it is not practical to add this to every occurrence in the whole site.


Solution

  • Regarding the inline scripts, there is a programmatic solution.

    You could write an Observer that binds to the core_block_abstract_to_html_after or controller_action_layout_render_before Events which fire immediately prior to outputting the rendered HTML. In your Observer, you could use a preg_replace to insert a head.ready statement immediately after each <script> tag.

    It would add a fraction more to the render time, but I suspect it would be less than the latency of downloading the libraries. And if you're using full page caching, then the function would only be called once.

    You could use the inbuilt Magento Profiler to test the impact. Worth a try at least.

    HTH,
    JD