Skip to content

Commit

Permalink
auto image inlining for css files
Browse files Browse the repository at this point in the history
  • Loading branch information
jairajs89 committed Nov 7, 2012
1 parent bd60111 commit a97b825
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 6 deletions.
2 changes: 1 addition & 1 deletion package.json
Expand Up @@ -2,7 +2,7 @@
"author": "Jairaj Sethi <j@jairaj.org> (http://jairaj.org/)",
"name": "zerver",
"description": "client-integrated webapp server",
"version": "0.5.3",
"version": "0.5.4",
"repository": {
"type": "git",
"url": "git://github.com/jairajs89/zerver.git"
Expand Down
66 changes: 61 additions & 5 deletions zerver.js
Expand Up @@ -11,9 +11,11 @@ var cleanCSS = require('clean-css'),

var ROOT_DIR = process.cwd(),
SLASH = /\//g,
GZIP_ENABLED = false,
CSS_IMAGE = /url\([\'\"]?([^\)]+)[\'\"]?\)/g,
GZIP_ENABLED = false,
COMPILATION_ENABLED = false,
CACHE_ENABLED = false,
INLINING_ENABLED = false,
CACHE_ENABLED = false,
GZIPPABLE = {
'application/json' : true ,
'application/javascript' : true ,
Expand Down Expand Up @@ -101,6 +103,7 @@ function configureZerver (port, apiDir, apiURL, debug, refresh, manifests, produ
if (!DEBUG && production) {
GZIP_ENABLED = true;
COMPILATION_ENABLED = true;
INLINING_ENABLED = true;
CACHE_ENABLED = true;
}

Expand Down Expand Up @@ -194,6 +197,57 @@ function handleMiddlewareRequest (request, response, next) {
handleRequest(request, response);
}

function inlineImages (type, data, pathname, callback) {
if (!INLINING_ENABLED || DEBUG) {
callback(data);
return;
}

data.replace(CSS_IMAGE, function (original, relativeURL) {
var urlParts;

try {
urlParts = url.parse(relativeURL, true);
}
catch (err) {
return original;
}

if ( !urlParts.query.inline ) {
return original;
}


var absoluteURL;

try {
absoluteURL = url.resolve(pathname, urlParts.pathname);
}
catch (err) {
return original;
}


var fileName = path.join(ROOT_DIR, absoluteURL),
fileData;

try {
fileData = fs.readFileSync(fileName).toString('base64');
}
catch (err) {
return original;
}


var mimeType = mime.lookup(fileName),
dataURL = 'data:'+mimeType+';base64,'+fileData;

return 'url(' + dataURL + ')';
});

callback(data);
}

function compileOutput (type, data, callback) {
if (!COMPILATION_ENABLED || DEBUG) {
callback(data);
Expand Down Expand Up @@ -296,9 +350,11 @@ function respond (handler, status, type, data, headers) {
function respondBinary (handler, status, type, data, headers) {
headers['Content-Type'] = type;

compileOutput(type, data, function (data) {
setupGZipOutput(type, data, headers, function (data, headers) {
finishResponse(handler, status, headers, data, true);
inlineImages(type, data, handler.pathname, function (data) {
compileOutput(type, data, function (data) {
setupGZipOutput(type, data, headers, function (data, headers) {
finishResponse(handler, status, headers, data, true);
});
});
});
}
Expand Down

0 comments on commit a97b825

Please sign in to comment.