Serve jQuery and jQuery-UI from Google's CDN

You are viewing revision #1 of this wiki article.
This version may not be up to date with the latest version.
You may want to view the differences to the latest version.

next (#2) »

There are good reasons to use Google's Content Delivery Network (CDN) to serve jQuery and jQuery UI on your site:

  1. Decreased latency
  2. Increased parallelism
  3. Better caching
  4. Reduced load on your server

(You can read more about them here.)

This tutorial shows you how to use Goggle's CDN to serve jQuery and jQuery UI in Yii.

Edit your Config File

There are two additions to make in your config file:

  1. Add a package definition for jQuery under the "clientScript" component in the "components" section
  2. Add a package definition for jQuery UI the "params" section
return array(
  // other config
  'components'=>array(
    'clientScript'=>array(
      'packages'=>array(
        'jquery'=>array(
          'baseUrl'=>'//ajax.googleapis.com/ajax/libs/jquery/1/',
          'js'=>array('jquery.min.js'),
        )
      ),
      // other clientScript config
    ),
    // other component config
  ),
  // other config

  'params'=>array(
    'jquery.ui'=>array(
      'theme'=>'dark-hive', // change to the theme you want to use
      'scriptUrl'=>'//ajax.googleapis.com/ajax/libs/jqueryui/1/',
      'themeUrl'=>'//ajax.googleapis.com/ajax/libs/jqueryui/1/themes/',
    ),
    // other params
  )
);

Note that the URLs are missing the protocol. This allows users browsers to cache both http and https requests from a single download.

For jQuery that is all that is needed.

For jQuery UI we need to tell JUI widgets to use the CDN; we do this when the configuring the widget in the view:

$jui = Yii::app()->params['jquery.ui'];
$this->widget('zii.widgets.jui.CJui<WidgetName>',array(
  'scriptUrl'=>$jui['scriptUrl'],
  'theme'=>$jui['theme'],
  'themeUrl'=>$jui['themeUrl'],
  // other widget config
));

where is the name of the JUI Widget (Tabs, DatePicker, etc.)

That's it - your application will now use Google's CDN to serve jQuery and jQuery UI; to the benefit of you and your visitors. It also means that a single change in the config file will change the theme of all your JUI widgets.

14 0
17 followers
Viewed: 42 613 times
Version: Unknown (update)
Category: Tutorials
Written by: Yeti
Last updated by: fad
Created on: Oct 18, 2011
Last updated: 11 years ago
Update Article

Revisions

View all history

Related Articles