开发者

How to use headjs with Joomla?

Trying to use HeadJS in Joomla. I added a code to my template - it grabs the javascript files in the head output, prepares a string to output them between head.js code, then removes 开发者_高级运维all javascript files from joomla's head output tag.

The problem is that some scripts are loaded after the template. For example, a module will enqueue some script files after the template has loaded, so its files appear outside of my head.js code. Any ideas how I can control this?

$data = $this->getHeadData();

if( $data['scripts'] ){
    foreach ($data['scripts'] as $url=>$type){
        if( !strstr($url, 'ajax.googleapis.com/ajax/libs/jquery') )
        $headjs[] = $url;
    }
    unset( $data['scripts'] );
    $data['scripts'][$template . '/js/head.js'] = array(
        'mime' => 'text/javascript',
        'defer' => false,
        'async' => false);
    $this->setHeadData($data);
}

And then...

 <script>
        head.js(
        <? foreach($headjs as $script): ?>
            '<?=$script?>',
        <? endforeach; ?>
            function(){
            }
        );
    </script>


Different extensions can hook up to different events that are triggered during processing the output (so even after template is rendered).

Best option I found so far is creating system plugin and moving it's order to be the last of available system plugins.

Now you have two options:

  1. use onBeforeCompileHead event (I guess introduced Joomla 1.5.23) to move scripts to headjs.
  2. use onAfterRender event and parse head html code so it's loaded using headjs.

This is fine if you play around with async scripts loading where you have total control over the website, but it's almost impossible to implement as universal extension for Joomla. Some extensions use inline scripts in head, some in the the html body and you'd have to preserve order of execution (simple example: Mootools have to load first).

I use to load asynchronously only those scripts which I've included myself (in my template or my extension). Any scripts that are added with Joomla core (Mootools, core.js, etc.) or other extensions I don't touch.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜