Nathan H
Nathan H

Reputation: 49371

Yii Make jQuery load first

Many modules, extensions or other things in Yii try to load jQuery from the asset manager. Which is fine, I've quit hardcoding the include and instead I am embracing 'registerCoreScript'.

The only issue is that it seems to be loading it near the bottom of the HEAD. I have a lot of other scripts and code that depend on jQuery, and they are loaded before it. How do I make sure that jQuery is the first thing loaded??

The truth is I don't understand how it's not the default behavior. jQuery doesn't depend on anything, but lots of scripts depend on it...

Upvotes: 1

Views: 5147

Answers (3)

ernie
ernie

Reputation: 6356

If the reference to hardcoded scripts in your comment means that you have <script> and <style> tags in your layout file in the <head>, then yes, using any of the Yii methods to register the script will result in that script coming last, as the Yii methods append the javascript to any existing content in the <head> (read the source if you want to verify).

Ideally, you should externalize the javascript into a separate file and load the file using registerScriptFile(). This makes things cleaner and easier to maintain.

Alternatively, you could use registerScript(), but that can be difficult to read/maintain.

When using these methods, items will be added in the order the methods are called.

Upvotes: 0

Oleksandr Vyshniakov
Oleksandr Vyshniakov

Reputation: 251

  1. Do not use hardcoded <script> tags in you html
  2. Put Yii::app()->clientScript->registerCoreScript('jquery'); at the beginning of your Controller::init() function.
  3. Include you own scripts using Yii::app()->clientScript->registerScriptFile('....');

Upvotes: 0

bool.dev
bool.dev

Reputation: 17478

You can use packages property of CClientScript component, and specify depends:

Yii::app()->clientScript->addPackage('give-some-name-to-script', array(
    'baseUrl'=>'base URL for the script files', // or basePath
    'js'=>array(list of js files relative to basePath/baseUrl),
    'depends'=>array('jquery')
));

Or do it this in config/main.php configuration:

'clientScript'=>array(
    'packages'=>array(
        'give-this-package-name'=>array(
            'basePath'=>'alias of the directory containing the script files',
            'js'=>array('first.js','second.js'),
            'depends'=>array('jquery')
    ),
)

And then use registerPackage:

Yii::app()->clientScript->registerPackage('your-package-name');

This is the only way that this can be done, i think. Of course this requires you to either group your javascript into a package and give it some name, or declare each script as a package.


Related answers: this and this

Upvotes: 4

Related Questions