Serve jQuery and jQuery-UI from Google's CDN

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 three additions to make in your config file:

  1. Define the JUI Theme you want to use.
  2. Add a package definition for jQuery under the "clientScript" component in the "components" section
  3. Set "theme", "scriptURL" and "themeURL" for each JUI Widget you use the "widgetFactory" section; the URLs point to Google's CDN, the theme uses the define from step 1.
define('JUI-THEME','dark-hive');
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
    ),
    'widgetFactory'=>array(
      'widgets'=>array(
        'CJui<WidgetName>'=>array( // where <WidgetName> is the name of the JUI Widget (Tabs, DatePicker, etc.). Each CJuiWidget used must be declared
          'scriptUrl'=>'//ajax.googleapis.com/ajax/libs/jqueryui/1/',
          'i18nScriptFile' => 'i18n/jquery-ui-i18n.min.js',
          'theme'=>JUI-THEME,
          'themeUrl'=>'//ajax.googleapis.com/ajax/libs/jqueryui/1/themes/',
        ),
        // Repeat for other CJuiWidgets
      ),
    ),
    // other component config
  ),
  // other config
);

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

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.

(Thanks to redguy for pointing out the widget factory configuration)

14 0
17 followers
Viewed: 43 610 times
Version: 1.1
Category: Tutorials
Written by: Yeti
Last updated by: fad
Created on: Oct 18, 2011
Last updated: 12 years ago
Update Article

Revisions

View all history

Related Articles