Merge CSS

Last modified by Vincent Massol on 2021/03/18 11:28

cogRead a CSS script, resolve all CSS imports and include them in place as a single CSS script
TypeSnippet
Category
Developed by

Ludovic Dubost

Rating
LicenseGNU Lesser General Public License 2.1

Table of contents

Description

Merge CSS is a groovy script allowing to read a CSS script and read all imports and include them in place.

This allows in conjunction with the tool on http://www.codebeautifier.com to create a unique merged CSS file more efficient for serving your skin's CSS file.

It doesn't recursively call the merge CSS and works only with relative urls in imports.

Code

#if($request.xpage=="plain")
{pre}
<%
url = request.url
baseurl = url.substring(0, url.lastIndexOf("/") + 1)
def css = xwiki.getURLContent(url)

def getCSS(name) {
def url = baseurl + name;
return xwiki.getURLContent(url);
}

def mergeCSS(css) {
 def pattern = /@import "(.*)";/
 def newcss = css.replaceAll(pattern, { it, name -> return getCSS(name); })
 return newcss;
}

response.setContentType("text/css")
println mergeCSS(css)
%>
{/pre}
#else
1 Merge CSS

This tools can be used with http://www.codebeautifier.com/ to provided a small css file. When you use codebeautifier, don't activate "Merge Selectors" as it seems to loose some background colors.

{pre}
<a href="$doc.getURL("view", "xpage=plain&url=http://www.xwiki.org/xwiki/bin/skin/Skin/SkinPage/style.css")">View merged CSS for xwiki.org</a>
{/pre}

You can use the following form to launch Merge CSS:

#if(!$request.url) 
#set($url = "http://www.xwiki.org/xwiki/bin/skin/Skin/SkinPage/style.css")
#else
#set($url = $request.url)
#end
<form action="">
<input type="hidden" name="xpage" value="plain" />
<input type="text" name="url" size="80" value="${url}" />
<input type="submit" value="Go" />
</form>

Here is an example URL to call Merge CSS using a URL:

http://server/xwiki/bin/view/Space/MergeCSSCode?xpage=plain&url=http://www.xwiki.org/xwiki/bin/skin/Skin/SkinPage/style.css
#end

Result

The result will be a CSS file. The url can be passed to codebeautifier. When you use codebeautifier, don't activate "Merge Selectors" as it seems to loose some background colors.

Get Connected