捕获并使用SASS文件中的所有图像URL,以便使用仅限css的预加载

时间:2013-09-13 07:57:20

标签: css regex sass

我最近开始使用css-only图像预加载项目的背景图像。

//preload images
body:after{  
    display: none;
    content: url(img01.png) url(img02.png);
}

//use images
li.one { background-image: (img01.png) }
li.two { background-image: (img02.png) }

我从SCSS制作我的CSS文件,并想知道是否有某些方法我可以使用SASS来运行文件并创建正文:从整个文件中的背景图像URL预加载后?

如果没有,那么在编译CSS文件后,制作一个使用Regex执行此步骤的脚本是什么?

2 个答案:

答案 0 :(得分:2)

@yorbro解决方案适用于这种特定情况,但我认为最好只使用一个函数同时执行这两项操作,将图像路径添加到$ preload-images列表并返回值。这是preload-img()函数:

// This declare a list variable to store all images to preload
$preloaded-images: ();

// This function will append the image or images to $preload-images and returns img path values
@function preload-img($img-path) {
    $output: ();
    @each $img in $img-path {
        $preloaded-images: append($preloaded-images, url($img));
        $output: append($output, url($img), comma);
    }
    @return $output;
}

使用此功能,您可以使用背景或背景图像属性,并且可以传递多个图像路径以创建多个背景。正如@yorbro所说,你应该在整个CSS的末尾添加body:after

// Use images, you can use background or background-image
// Note that you can pass a list of paths to preload-image function
li.one { background: preload-img("img01.png" "img02.png"); }
li.two { background-image: preload-img("img02.png"); }

//preload images
body:after{
    display: none;
    content: $preloaded-images;
}

答案 1 :(得分:1)

您可以使用SASS mixins,函数和列表。首先,您创建一个mixin background-image,它将添加background-image属性,并将图像附加到SASS列表preload-images

/* '$img-path' is in your case 'img01.png' or 'img02.png' */
@mixin background-image($img-path) {
  background-image: url($img-path);
  $tmp: preload-image($img-path);
}

然后定义函数preload-image以及列表$preloaded-images。该函数将url($img-path)附加到$preloaded-images列表。

/* Preloaded images */
$preloaded-images: null;
@function preload-image($image-path) {
  $preloaded-images: $preloaded-images url($image-url);
  @return $preloaded-images;
}

每次要使用背景图片时,都使用background-image mixin。然后,在整个CSS文件的末尾,添加body:after表达式。这很重要,因为您需要在输出body:after表达式之前将所有预加载的图像添加到列表中。所以

//use images
li.one { @include background-image("img01.png"); }
li.two { @include background-image("img02.png"); }

//preload images
body:after{  
  display: none;
  content: $preloaded-images;
}

结论:SASS作为一种语言在某些方面受到限制,但仍然足以实现这些美好的事物!