Question

I would like to configure my environment to serve css and javascript files from static.example.com instead of example.com/static.

The second has the convenience that I can code my html pages to load the css and javascript files relatively eg "static/reset.css" independent of the actual domain.

Is there a good practice to avoid altering all my source files whenever I change

static.example.com to static.otherexample.com

as I would have to rewrite all my HTML source files importing css and javascript?

Was it helpful?

Solution

Use some kind of configurable prefix to include js and css files. Depending on the technology you're using, it is helpful to have some kind of helper method for this. In ASP.NET MVC, I use some custom method like CSS.Add("reset.css"), which knows the path and URL.

The js files should not really care where they are loaded from. As for css, it's important to know that relative URLs in CSS are interpreted as relative to the URL the CSS was loaded from, not relative to the URL the page was loaded from. So make sure you understand that background-image: url('/images/img1.png') would also load from the static page (which is usually a good thing).

The better way

It's best practice to compress, minify and merge all of the CSS / js files. Therefore, you should only have a very small number of files (one js, one css) to keep the number of requests low. The inclusion of these files would happen on the server, so the URLs don't matter. To implement this, you will need some kind of helper method (and a lot of compression logic, but there are libraries for all this).

For ASP.NET MVC there is SquishIt, but I'm sure there are plenty of tools for various environments.

OTHER TIPS

How is the html being generated?

You could use a config value or constant, and use that value for the domain portion of the url for any of the static assets.

You can always do a trick on the server, i.e. all your urls in HTML could be relative to /static, but once your server receive request, it can "change" the route and get files from static.current-domain.com instead of current-domain.com/static

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top