Skip to content

Instantly share code, notes, and snippets.

@metaphox
Created August 22, 2013 20:49
Show Gist options
  • Select an option

  • Save metaphox/6312610 to your computer and use it in GitHub Desktop.

Select an option

Save metaphox/6312610 to your computer and use it in GitHub Desktop.
styleSheetRaw = null;
fileSystem = null;
imgDataURIs = {};
imgBgStyle = $('#img-bg-style');
bgStyleUrl = imgBgStyle.attr('href');
function useLocalImages(msg){
console.log(msg);
if(null === styleSheetRaw|| null == fileSystem){
return;
}
var imgurls = [];
// this is not really a replace, but just finding out all unique URLs
var unique = {};
styleSheetRaw.replace(/(url\()(.*?)(\))/gi, function(m, p1, p2, p3){
if(p2.match(/https?:\/\//i)) return;
p2 = p2.replace(/"/g, '').replace(/\.\./, '');
if(unique.hasOwnProperty(p2)) return;
unique[p2] = 1;
imgurls.push(p2);
});
var counter = imgurls.length;
// apply local images as data URI for all url() calls in the raw style
// sheet
var applyLocalImageAsDataURI = function(msg){
//console.log(msg);
counter--;
// wait till all images are loaded
if(counter > 0) return;
alert("done all image to base 64 conversion");
//return;
//console.log("all done");
var styleSheetConverted = styleSheetRaw.replace(
/(url\()(.*?)(\))/gi, function(m, p1, p2, p3){
if(p2.match(/https?:\/\//i)) return p1+p2+p3;
var naked = p2.replace(/"/g, '').replace(/\.\./, '');
if(imgDataURIs.hasOwnProperty(naked)){
return p1+imgDataURIs[naked]+p3;
}
return p1+p2+p3;
});
$('body').append(
styleSheetConverted
);
};
for(var i = 0, len = imgurls.length; i < len; i++){
var url = imgurls[i];
var imgPath = "file://" + fileSystem.root.fullPath + url;
(function(){
var fileUrl = url;
window.resolveLocalFileSystemURI(imgPath, function(fileEntry){
fileEntry.file(function(file){
var reader = new FileReader();
reader.onloadend = function (evt) {
var base64content = evt.target.result;
if (!base64content) { return; }
imgDataURIs[fileUrl] = base64content;
applyLocalImageAsDataURI("found " + fileUrl);
};
reader.readAsDataURL(file);
});
},
function(e){ applyLocalImageAsDataURI("not found " + fileUrl); });
})();
}
}
// Wait for device API libraries to load
//
document.addEventListener("deviceready", function(){
console.log(typeof window.requestFileSystem);
$.get(bgStyleUrl, function(data){
//join all lines into a single line string and consolidate whitespaces
data = data.replace(/(\r\n|\n|\r)/gm, " ").replace(/\s+/g, " ");
//remove comments
data = data.replace(/\/\*.*?\*\//g, '');
styleSheetRaw = data;
useLocalImages("from ajax");
});
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(pFileSystem){
console.log("got FS");
fileSystem = pFileSystem;
},
function(){
console.log('no can do.');
});
}, false);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment