Skip to content

Instantly share code, notes, and snippets.

@lgh06
Last active April 25, 2016 13:54
Show Gist options
  • Save lgh06/75bd3e8f062c4111d5f489999a351f1f to your computer and use it in GitHub Desktop.
Save lgh06/75bd3e8f062c4111d5f489999a351f1f to your computer and use it in GitHub Desktop.
a js file conbines csses to inline css,used in phantomjs
var j = document.createElement('script');
j.async = "async";
j.src = 'https://lib.sinaapp.com/js/jquery/1.10.2/jquery-1.10.2.min.js';
j.onload = genPic;
document.querySelector('head').appendChild(j);
function genPic(){
// // Code taken from MatthewCrumley (http://stackoverflow.com/a/934925/298479)
// function getBase64Image(img) {
// // Create an empty canvas element
// var canvas = document.createElement("canvas");
// canvas.width = img.width || 1;
// canvas.height = img.height || 1;
// // Copy the image contents to the canvas
// var ctx = canvas.getContext("2d");
// ctx.drawImage(img, 0, 0);
// // Get the data-URL formatted image
// // Firefox supports PNG and JPEG. You could check img.src to guess the
// // original format, but be aware the using "image/jpg" will re-encode the image.
// var dataURL = canvas.toDataURL("image/png");
// return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
// }
// var i = document.createElement('img');
// i.src = "https://developer.cdn.mozilla.net/static/build/styles/mdn.593f20d8c365.css"
// var bs = getBase64Image(i);
// console.log(bs)
var cssSheets = document.styleSheets;
var keys = Object.keys(cssSheets);
var inline = '';
if(keys.length){
keys.forEach(function (v,i,a) {
console.log(cssSheets[v])
//cssSheets[v].cssRules CSSRuleList
if( cssSheets[v] && cssSheets[v].cssRules && Object.keys(cssSheets[v].cssRules).length){
Object.keys(cssSheets[v].cssRules).forEach(function (vv,ii,aa) {
//cssSheets[v].cssRules[vv] CSSStyleRule
inline+=cssSheets[v].cssRules[vv].cssText;
});
}
if(cssSheets[v] && ! cssSheets[v].cssRules){ //ajax load
$.ajax({
method:'GET',
url:cssSheets[v].href,
type:'plain',
'async':false,
success:function(data){
console.log(data);
inline+=data;
}
});
}
});
}
console.log(inline)
var styles = document.querySelectorAll('style');
if(styles.length){
Object.keys(styles).forEach(function (v,i,a) {
styles[v].parentNode.removeChild(styles[v]);
});
}
var newStyle = document.createElement('style');
console.log(inline)
newStyle.innerHTML = inline;
document.querySelector('head').appendChild(newStyle);
var allHtml = document.querySelector('html').outerHTML;
var file = new Blob([allHtml],{type:'text/html'});
//var base64 = window.URL.createObjectURL(file);
var reader = new FileReader();
reader.addEventListener("load", function () {
var a = document.createElement('a');
a.download = 'download';
a.href = reader.result;//base64;
a.click();
//window.location.href = a.href;
}, false);
if (file) {
reader.readAsDataURL(file);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment