开发者

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-lin开发者_JAVA百科e 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.


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


well, i use jquery for this. and it works great.
All you have to do is to make an ajax request that returns the script and then evaluate the script using eval. You can write your own function for this, but jquery already has some nice approaches.
For single scripts, the $.getScript function works well. It's basically an extension of the $.ajax function that specifies that you are requesting a script. the syntax is like this :

$.getScript('my_script_url',function(){
    // do whatever needs to be done after the script loads
    alert('my script was asynchroniously loaded');
});

If you have more scripts that you want to add through ajax, jquery has a neet way of doing this :

$.when(
    $.getScript("/script_1.js"), 
    $.getScript("/script_2.js"), 
    $.getScript("/script_3.js")
    // ...
    //$.getScript("/script_n.js")
).then(
    // on succes
    function(){
        alert('good to go!');
    },
    // on failure
    function(){
        alert('loading failed. one or more scripts encountered a problem :(');
    }
);


All loaders of this nature are going to require some modification to every script on your site. I know--I just implemented LABjs on a system which, when I grepped, showed over 400 files with some sort of script tag!!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜