Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add replaceCSSImageURLs #10

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,4 +86,14 @@ Looks for data-url(filepath/file.png) in the CSS and replaces those with the con
Simply replaces `data-url` with `url`. Used as a complement with replaceImageRefToBase64 if you want to serve a css to IE6-7.

### fixFloatDoubleMargin
Finds all blocks containing floats and add a display: inline; (unless there is another display set in that block) to fix double margin bugs.
Finds all blocks containing floats and add a display: inline; (unless there is another display set in that block) to fix double margin bugs.

### replaceCSSImageURLs
Finds all relative CSS image URLs, and replaces them to be absolute. THis ensures that there are no broken image references, even if loading images to the asset manager from different directories.

Arguments:

* **Root** - The root directory of your server. Not the public folder, but your server.

#### Setup
assetHandler.replaceCSSImageURLs(root)
47 changes: 47 additions & 0 deletions lib/handlers.js
Original file line number Diff line number Diff line change
Expand Up @@ -188,4 +188,51 @@ function handlers()
}
}));
};
this.replaceCSSImageURLs = function(root) {

return function(file, path, index, isLast, callback) {

var relativePath = path.replace(root, '');

var segments = relativePath.split('/');
delete segments[segments.length - 1];

relativePath = segments.join('/');

var regex = /url\([^\)]*\)/;
var matches = [];
var tmpFile = file;
while (regex.test(tmpFile) !== false) {
var match = regex.exec(tmpFile)[0];
matches.push(match);
tmpFile = tmpFile.replace(match, '');
}

for (var i = 0; i < matches.length; i++) {
var result = matches[i];
var s = result;
var hasQuotes = (s.indexOf('url("') !== -1 || s.indexOf("url('") !== -1);
if (hasQuotes)
s = s.substring(5, s.length - 2);
else
s = s.substring(4, s.length - 1);

var external = false;
if (s.indexOf("http://") === 0) external = true;
if (s.indexOf("https://") === 0) external = true;
if (s.indexOf("/") === 0) external = true;

if (external === true)
continue;

var newURL = relativePath + s;

file = file.replace(result, "url('" + newURL + "')");
}

callback(file);

}

};
}