Getting root path in Javascript files included in Yii application

A server-side root path in client-side Javascript code? Are you mad? Why would I need this? Well… For example, when referencing image files (placed on server, right?), that are using dynamic paths or for any other reasons can’t be added statically (for example using CSS).

Getting root path in Javascript files is a hard task itself. When do you need to combine this problem with Yii client-assets publishing mechanism, it can become even harder. However, I found nice, clean and simple solution, using HTML5’s data- attributes.

The only pity thing is, that I don’t remember its original author.

The solution is really simple. First, declare new attribute on your body (in your main layout file):

[code language=”php”]
<body data-root="<?php echo(Yii::app()->request->baseUrl); ?>">
[/code]

Then, simply read it in your Javascript file:

[code language=”javascript”]
$(function()
{
var rootPath = document.body.getAttribute("data-root");

$.blockUI.defaults.message = ‘<img src="’ + rootPath + ‘/img/wait.gif" width="48" height="48" />Busy…’;
});
[/code]

We’re talking about Yii here, right? That means, you can’t use relative paths (the easiest approach), because they vary on actual URL, which (in Yii) contains controller and action and sometimes also module name — all this stuff that makes relative paths in Javascript simply unusable.

Once again — this is only a snippset or example of solution. The entire problem can by much easier and faster solved, using CSS and a class with static path to file used as some object background.

Or even, fabulous Font Awesome library:

[code language=”javascript”]
$.blockUI.defaults.message = ‘<i class="icon-spinner icon-spin icon-large"></i>Operation in progress…’;
[/code]

Yes, I know that. I only wanted to show an alternative approach. Is that fine with you?

Note, that you have to use CSS-based approach, if you want to use an image anywhere withing onbeforeunload event. Since there is a nasty bug in Chrome and Firefox (or this is undocumented standard, that only IE breaks again), images referenced by <img /> tag aren’t shown, when object containing then is displayed at onbeforeunload. In this StackOverflow question you should find more details.

Again, I’m really sorry, that I don’t remember original author of this solution.

Leave a Reply