How to Use Yii clientScript scriptMap to speed up your website

My pet project site was running quite slowly due to the large number of http request going and waiting for many different stylesheets and scripts that my site required to have. Certainly, there are available php script that can combine all my stylesheets and scripts into 1 big file but doing this would had already use up certain amount of resources needed to perform such compilation. Yii had already provide such method within their framework which is called scriptMap. However, scriptMap is pretty confusing and i did spend sometime figuring it out before finding it useful. Hence, writing this down would definitely serve a good purpose in the future.

What is Yii scriptMap

Yii scriptMap is a method within the clientScript class that allows you to map a particular script or stylesheet into a desirable file. It is like htaccess rule to perform redirect whenever you see a particular URL, redirect it. The same concept apply to scriptMap. Whenever you see a particular script or stylesheet, print the one that i want instead of the one you see.

How Yii scriptMap works?

I believe there are a few things to point out on Yii scriptMap before actually show you the snippet of scriptMap.

  • Yii scriptMap do not print out your stylesheet or script for you
  • Yii scriptMap doesn't work like registerScriptFile or registerCssFile (which print out your file)
  • Yii scriptMap will not map if it doesn't see the script or stylesheet you have placed on the function. Hence, you still see the same script/stylesheet.
  • Yii scriptMap directory start below the directory level of 'protected'. Hence, its at the level where you see all the css/assest/js/theme folder.
  • Please ensure the file you are mapping to, had already exist.

Once you understand the above. It is time to show you how this is being done.

2 thoughts on “How to Use Yii clientScript scriptMap to speed up your website

Comments are closed.