Image paths in CSS to support CDN
Asked Answered
I

1

16

I am trying to deploy our images to a cdn. Currently the css has relative paths to images on our site. These paths will need to support the CDN image location. Does anyone have advice on how I can do this?

Or if anyone has a good tutorial on deploying to a CDN.


This is how I ended up accomplishing this.

  1. I used SASS - http://sass-lang.com/
  2. I have a mixin called cdn.scss with content like $image_path: "/images/";
  3. Import that mixin in the sass style @import "cdn.scss"
  4. Update image paths as such: background: url($image_path + "image.png");
  5. On deployment I change the $image_path variable in the mixin.scss and then rerun sass

UPDATE

We use bash to update the file

cat > preprocess/sass/_cdn.scss <<EOT
\$image_path: "//CDN_URL/";

Example code in the _cdn.scss

$image_path: "/public/images/";

Then it works by default locally, but on production push, we run the bash script to update using the cdn location

Irritate answered 3/10, 2010 at 1:11 Comment(1)
I have since changed the cdn.scss file to be _cdn.scss so it does not output a file, but is only used as a mixin.Irritate
R
18

Probably the easiest thing would be to host both your images and CSS file on the CDN. Image paths in your CSS file are relative to the CSS file itself, so you won't have to change your CSS at all.

If that's not an option, you're stuck putting the fully qualified URLs in your stylesheet. Now, if you really wanted to, you could generate your CSS file dynamically on the fly, and perform some replacement so you don't actually have to hard code the CDN in your sheet.

Remembrance answered 3/10, 2010 at 1:55 Comment(3)
We can not have image paths relative. We decided to use a compiled css SASS for the style sheets and a script that we run on deployment to change the SASS variables. But for most cases your answer is correct.Irritate
@Irritate Nice. Could you share abit more detail around how that script changes the SASS variable? Is it a bash script, or something else?Brott
@Remembrance have the rules changed in the last 10 years? Are the rules the same across all modern browsers?Greek

© 2022 - 2024 — McMap. All rights reserved.