Coder Social home page Coder Social logo

grunt-criticalcss's Introduction

โš ๏ธ This project is archived and the repository is no longer maintained.

grunt-criticalcss

Grunt wrapper for criticalcss

Getting Started

This plugin requires Grunt ~0.4.2

If you haven't used Grunt before, be sure to check out the Getting Started guide, as it explains how to create a Gruntfile as well as install and use Grunt plugins. Once you're familiar with that process, you may install this plugin with this command:

npm install grunt-criticalcss --save-dev

Once the plugin has been installed, it may be enabled inside your Gruntfile with this line of JavaScript:

grunt.loadNpmTasks('grunt-criticalcss');

The "criticalcss" task

Overview

In your project's Gruntfile, add a section named criticalcss to the data object passed into grunt.initConfig().

grunt.initConfig({
  criticalcss: {
    custom: {
      options: {
        // Task-specific options go here.
      }
    }
  },
});

Options

options.url

Type: String Default value: ''

REQUIRED: A string for the URL of the site you'd like to run this script against

options.filename

Type: String Default value: all.css

A string value for the entire path of a css file that you have hosted locally.

options.width

Type: Integer Default value: 1200

An integer value of the width of the screen in pixels

options.height

Type: Integer Default value: 900

An integer value of the height of the screen in pixels

options.outputfile

Type: String Default value: dist/dist.css

A string value that is the file path for wherever you would like the css to be output to

options.forceInclude

Type: Array Default value: []

An array of selectors that you want to guarantee will make it from the CSS file into your CriticalCSS output.

options.buffer

Type: Integer Default value: 800*1024

Sets the maxBuffer for child_process.execFile in Node. Necessary for potential memory issues.

options.ignoreConsole

Type: Boolean Default value: false

If set to true, will silence any outputs to console in the page's JavaScript

options.restoreFontFaces

Type: Boolean Default value: false

If you include @font-face declarations in your all.css file and set this flag to true in your options, criticalcss will include all the @font-face declarations that are required to satisfy font-family declarations in the criticalcss output.

Usage Examples

Custom Options

grunt.initConfig({
	criticalcss: {
		custom: {
			options: {
				url: "http://localhost:4000",
				width: 1200,
				height: 900,
				outputfile: "dist/critical.css",
				filename: "/path/to/local/all.css", // Using path.resolve( path.join( ... ) ) is a good idea here
				buffer: 800*1024,
				ignoreConsole: false
			}
		}
	},
});

Contributing

In lieu of a formal style guide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality. Lint and test your code using Grunt.

Release History

  • v0.5.0 - Add support for ignoreConsole
  • v0.4.0 - Add support for buffer size, so you don't exceed the buffer
  • v0.3.0 - Moved to using a local filename instead of a pattern-match
  • v0.2.0 - Added forceInclude functionality.
  • v0.1.0 - Original release

grunt-criticalcss's People

Contributors

jefflembeck avatar johnbender avatar lucalanca avatar mozmorris avatar paulirish avatar scottjehl avatar trott avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

grunt-criticalcss's Issues

Only getting -webkit- properties from stylesheet instead of un-prefixed version

Hi,

Noticed an issue with the output .css file stripping all of the class vendor prefixes and only choosing the -webkit- version. Here is an example of what I keep getting:

My class pre critical task:

.flex-box { display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-flex-direction: row; -webkit-box-orient: horizontal; -webkit-box-direction: normal; -ms-flex-direction: row; flex-direction: row; -webkit-align-items: center; -webkit-box-align: center; -ms-flex-align: center; align-items: center; -webkit-justify-content: center; -webkit-box-pack: center; -ms-flex-pack: center; justify-content: center; }

The class after critical task:

.flex-box{-webkit-box-orient:horizontal}

It doesn't seem to be just with flex box, this is the output for a transform:

Before critical task:

.current-menu-item a:after { opacity: 1; -webkit-transform: translateY(0); -ms-transform: translateY(0); transform: translateY(0); }

After critical task :

.current-menu-item a:after{opacity:1;-webkit-transform:translateY(0)}

This is my Gruntfile:

module.exports = function(grunt) {
var critical = grunt.file.readJSON('critical/critical.php');
var files = [];
var options = {};
critical.pages.forEach(function(page) {
options[page.name + 'Desktop'] = {
options: {
url: page.url,
width: 1200,
height: 900,
outputfile: "critical/critical-"+ page.name +".css",
filename: "style.css",
buffer: 800_1024,
ignoreConsole: true,
forceInclude: ['.flex-box', '.flex-end']
}
};
options[page.name + 'Mobile'] = {
options: {
url: page.url,
width: 320,
height: 500,
outputfile: "critical/critical-"+ page.name +"-mobile.css",
filename: "style.css",
buffer: 800_1024,
ignoreConsole: true,
forceInclude: ['.flex-box', '.flex-end']
}
};
files.push('critical/critical-'+page.name+'.css', 'critical/critical-'+page.name+'-mobile.css');
});
grunt.initConfig({
criticalcss: options,
postcss: {
options: {
processors: [
require('autoprefixer')({browsers: 'last 6 versions'}), // add vendor prefixes
require('cssnano')() // minify the result
]
},
dist: {
src: files
}
}
});
grunt.loadNpmTasks('grunt-criticalcss');
grunt.loadNpmTasks('grunt-postcss');
grunt.registerTask('default', ['criticalcss', 'postcss']);
};

(how can I format this properly? Using the code button made it all weird and minified)

I tried using the forceRequire to try and get phantomJS to ignore the style, but I keep getting the same output.

Am I missing something important here?

Thanks in advance for any help, I really enjoy using the plugin! :)

Option to extend timeout or handle promise rejection?

I have grunt-criticalcss running in the background of a production environment, but one of the last hurdles I have to overcome is the issue with my environment where most pages on their first load, before they are processed by grunt, take longer than 30 seconds to load. (They load in under 2 seconds in subsequent loads after processing).

The logs I've reviewed show that the process times out after 30 seconds with the following error (I've censored out my local data):

UnhandledPromiseRejectionWarning: Error: Navigation Timeout Exceeded: 30000ms exceeded
  at /**********/node_modules/grunt-criticalcss/tasks/criticalcss.js:43:12
  at /**********/node_modules/criticalcss/critical.js:115:20

I'm just using the built-in functionality (no customization other than passing the options provided for in the documentation) using grunt.initConfig().

n my limited knowledge of the underlying programming, I see two possible solutions:
(1) Handle the promise rejection; and/or
(2) Create an option allowing for execution to be extended past the 30 second time limit.

Js Responsiveness (@media queries, resolutions, etc...)

Hello. Your script works fine but here some things I'd like to have or to know how to make it works if it is already possible.

  1. It is seem that your module does not allow to work with the different dimensions. it only has properties "width" and "height". For example another npm package grunt-critical has much more options and an ability to point several dimensions like in that way "dimensions": [ {width: 800, height: 600}, {width: 500, height: 350} ].
  2. Your module does not ability to proceed with HTML (or DOM) markup which is changed by JavaScript. So if
    is changed to
    then .class.active selector won't be picked up by your module. The only way to solve this issue is to use forceInclude. Does firceInclude option allows to include media queries to its array? Do you plan to develop a feature which will allow to see changes in DOM by JavaScript?

p.s. By the way grunt-critical is based on critical which is based on penthouse . And the last one has huge functionality and there is inheritance of features and options to run.
Don't you plan to expand your functionality? :)

[Request] Multipage support, CSS slicing

This thing is freaking awesome. Here are couple things I noticed that would bring criticalcss to the next level.

Multipage Support

Pass in an array of URLs (or .html files local to Grunt root) and have the option for criticalcss to either create a single bundle with all the common styles between the pages passed in, or spit out separate files, one for each url/page. Useful for sites that have multiple high-traffic landing pages.

CSS Slicing

Add an option to slice out and remove the selectors that are determined to be ATF from the source CSS file (thus saving kb that would be downloaded twice).

Strange Compile Issue

Getting a very strange issue, when compiling the critical output. For some reason it's nesting selectors inside selectors, with normal CSS.

This is part of the source CSS that gets fed into Critical:

.icon {
  display: inline-block;
  font-family: 'Glyphicons Halflings';
  font-style: normal;
  font-weight: normal;
  line-height: 1;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

.icon--pencil::before {
  content: "\e600";
}

.icon--lock::before {
  content: "\e601";
}

.icon--external-arrow::before {
  content: "\e602";
}

.icon--location::before {
  content: "\e603";
}

.icon--spinner::before {
  content: "\e604";
}

.icon--search::before {
  content: "\e605";
}

.icon--cancel-circle::before {
  content: "\e606";
}

.icon--checkmark::before {
  content: "\e607";
}

.icon--arrow-left::before {
  content: "\e608";
}

.icon--map::before {
  content: "\e609";
}

.icon--calendar::before {
  content: "\e60b";
}

.icon--users::before {
  content: "\e60c";
}

.icon--minus::before {
  content: "\e60d";
}

.icon--plus::before {
  content: "\e60e";
}

@keyframes spin {
  100% {
    transform: rotate(360deg);
  }
}

The icon classes are not part of the critical path, but are getting included for some reason. The keyframe syntax is required (it's used later for a loading spinner), so I'm not sure if maybe it's getting confused by that, and for some reason pulling in a load of preceding classes, but breaking them...

Anyway, here is what Critical outputs. Note the search, checkmark, calendar and minus classes.

.icon--pencil::before {
  content: "\e600";
}

.icon--lock::before {
  content: "\e601";
}

.icon--external-arrow::before {
  content: "\e602";
}

.icon--location::before {
  content: "\e603";
}

.icon--spinner::before {
  content: "\e604";
}

.icon--search::before {

.icon--checkmark::before {

.icon--map::before {
  content: "\e609";
}

.icon--calendar::before {

.icon--minus::before {

@keyframes spin {
  100% {
    transform: rotate(360deg);
  }
}

.container {
  width: 100%;
  margin-left: auto;
  margin-right: auto;
  margin-top: 20px;
  margin-bottom: 20px;
  max-width: 62.5rem;
}

.container comes from later in the source CSS, and is correct, but obviously, because of those unclosed classes, the CSS is invalid, so none of the CSS after them gets parsed (which is most of the critical path stuff), until the full CSS file loads later and everything starts working.

I'm pretty lost on this one. Any help appreciated!

Use --ignore-ssl-errors=yes for local secure sites

When trying to use this on my local secure site, Phantom JS gives the following error:

Fatal error: PHANTOM ERROR: Error: Page didn't open: https://theindividualagency.local TRACE: -> /Users/keironlowe/Development/The Individual Agency/theindividualagency.co.uk/node_modules/grunt-criticalcss/node_modules/criticalcss/lib/criticalrunner.js: 61 -> :/modules/webpage.js: 281PhantomJS has crashed. Please read the crash reporting guide at https://github.com/ariya/phantomjs/wiki/Crash-Reporting and file a bug report at https://github.com/ariya/phantomjs/issues/new with the crash dump file attached: /tmp/E494F362-367B-4622-A15A-FBCB2151DF75.dmp

I believe this is due to the fact that the ssl certificate from Mamp Pro is self signed, and gives an SSL error when you first visit the site. Looking at this stack overflow post, it can be fixed by adding the --ignore-ssl-errors=yes flag when calling Phantom.

Question about flat sites from email

Iโ€™d like to use CriticalCSS in projects that are basically flat file sites that include a handful of PHP partials, and also in Wordpress sites. Am I risking anything or basically doing it wrong if I use CriticalCSS in my build process for these kinds of projects?

exclude class

Hello ,

i want to ask about excluding unwanted classes is it possible and how?

404 Handling

I haven't necessarily seen any other tickets but I figured it'd be something to look into.

If a URL is referenced that winds up 404ing from what I can tell the critical css is still generated for that particular page.

Ideally you'd see some sort of error indicator that the URL being referenced has an issue and may no longer be valid. I could anticipate long term if this is not addressed it opens a pretty wide area of degraded performance. I've tested this in our local and dev environments.

Task runs but no output

When I run grunt criticalcss I get the 'Done. without errors' message, but no output file is written.

Hoping I'm just missing something in my config:

criticalcss: {
options: {
url: "http://localhost/index.shtml",
            width: 1200,
            height: 900,
            outputfile: "html/css/build/critical.css",
            filename: "html/css/build/dh.min.css",
            buffer: 800*1024
}
},

Force include selector with camelCase

Hi,

I found an issue when you have a selector like #pbOverlay which is being used by a plugin (I dont agree with the naming convention) that if you try and forceInclude this selector it doesn't include it in the generated css

is there a work around other than changing my css selector / adding these selectors in manually?

Inline SVG background image breaks criticalcss workflow

Hey everyone, I have a SVG icon that is being inlined into the background-image property of a css rule and it's breaking my criticalcss workflow...
The specific css rule with the problem svg is as follows:

background-image:url("data:image/svg+xml;charset=UTF-8,%3csvg id='Layer_1' data-name='Layer 1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' viewBox='0 0 1797.1 1864.9'%3e%3cdefs%3e%3cstyle%3e.cls-1%7bfill:url(%23linear-gradient);%7d.cls-2%7bopacity:0.15;isolation:isolate;%7d.cls-3%7bfill:url(%23linear-gradient-2);%7d.cls-4%7bfill:url(%23linear-gradient-3);%7d.cls-5%7bfill:url(%23linear-gradient-4);%7d%3c/style%3e%3clinearGradient id='linear-gradient' x1='-170.4429' y1='-325.2993' x2='-171.0945' y2='-326.0254' gradientTransform='translate(175363.897 194278.2402) scale(1019.2484 595.6411)' gradientUnits='userSpaceOnUse'%3e%3cstop offset='0' stop-color='%2380c3e6'/%3e%3cstop offset='1' stop-color='%233380c2'/%3e%3c/linearGradient%3e%3clinearGradient id='linear-gradient-2' x1='-170.0279' y1='-324.0137' x2='-170.8561' y2='-324.3363' gradientTransform='translate(103678.3423 330781.0342) scale(599.4398 1016.2092)' gradientUnits='userSpaceOnUse'%3e%3cstop offset='0' stop-color='%23f38649'/%3e%3cstop offset='0.1849' stop-color='%23f28147'/%3e%3cstop offset='0.4091' stop-color='%23ef7242'/%3e%3cstop offset='0.6537' stop-color='%23ea5a3a'/%3e%3cstop offset='0.911' stop-color='%23e4382e'/%3e%3cstop offset='1' stop-color='%23e12a29'/%3e%3c/linearGradient%3e%3clinearGradient id='linear-gradient-3' x1='-171.3452' y1='-323.8776' x2='-170.5824' y2='-324.4617' gradientTransform='translate(213490.8682 329942.4446) scale(1245.2634 1016.2094)' gradientUnits='userSpaceOnUse'%3e%3cstop offset='0' stop-color='%2342ab4a'/%3e%3cstop offset='1' stop-color='%23add155'/%3e%3c/linearGradient%3e%3clinearGradient id='linear-gradient-4' x1='-171.079' y1='-323.8036' x2='-170.5348' y2='-325.2896' gradientTransform='translate(243030.7075 271120.8525) scale(1418.6571 831.5027)' xlink:href='%23linear-gradient-3'/%3e%3c/defs%3e%3ctitle%3emodx-logo-svg-vector%3c/title%3e%3cpath class='cls-1' d='M1419.8,780l372.3-595.6H896.6L772.9,382.9,1419.8,780Z'/%3e%3cpath class='cls-2' d='M772.9,382.9,836.3,281l583.6,499-647-397.1Z'/%3e%3cpath class='cls-3' d='M1616.8,1859.9V964.5L1423.6,843.7l-406.2,641.7,599.4,374.5Z'/%3e%3cpath class='cls-2' d='M1017.3,1485.4l100.3,62.7,305.9-704.3-406.2,641.6Z'/%3e%3cpath class='cls-4' d='M174.4,5.2V900.7l207.2,120.7L1419.7,779.9Z'/%3e%3cpath class='cls-5' d='M377.3,1089.7,5,1675.2H900.5l523.2-831.5Z'/%3e%3c/svg%3e");

it produces the following error:

[CriticalCSS] Error thrown in criticalcss.findCritical while processing original.css: Error: undefined:719:395: missing '}'

Any thoughts/help on how to resolve this? I'm running grunt-criticalcss in a production workflow (it runs in the background when a page request is made and the next page call that is executed after the critical css is generated calls the result). This issue is cropping up as part of my cronjob that routinely compresses the CSS in cached webpages on my server...

Getting Phantom Error on Google +1 share button

I get the following error when running both file path or URL (url if it helps http://www.mikelonsdale.co.uk).

Running "criticalcss:custom_options" (criticalcss) task

Something went wrong with phantomjs...
PHANTOM ERROR: Error requesting /_/scs/apps-static/_/js/k=oz.gapi.en_GB.rtBP98PsisY.O/m=googleapis_client,iframes_styles_bubble_internal,iframes/rt=j/sv=1/d=1/ed=1/am=UQ/rs=AItRSTPC6XpWJcUcEMEo2aHNHe_1oFgl3A/cb=gapi.loaded_0: 
Current location: https://plusone.google.com/_/+1/fastbutton?bsv&size=standard&count=true&hl=en-US&origin=file%3A%2F%2F&url=http%3A%2F%2Fwww.mikelonsdale.co.uk%2F&ic=1&jsh=m%3B%2F_%2Fscs%2Fapps-static%2F_%2Fjs%2Fk%3Doz.gapi.en_GB.rtBP98PsisY.O%2Fm%3D__features__%2Fam%3DUQ%2Frt%3Dj%2Fd%3D1%2Frs%3DAItRSTPC6XpWJcUcEMEo2aHNHe_1oFgl3A#_methods=onPlusOne%2C_ready%2C_close%2C_open%2C_resizeMe%2C_renderstart%2Concircled%2Conload&id=I0_1405620467511&parent=file%3A%2F%2F&rpctoken=27602086
Fatal error: Error: Command failed: PHANTOM ERROR: Error requesting /_/scs/apps-static/_/js/k=oz.gapi.en_GB.rtBP98PsisY.O/m=googleapis_client,iframes_styles_bubble_internal,iframes/rt=j/sv=1/d=1/ed=1/am=UQ/rs=AItRSTPC6XpWJcUcEMEo2aHNHe_1oFgl3A/cb=gapi.loaded_0: 
Current location: https://plusone.google.com/_/+1/fastbutton?bsv&size=standard&count=true&hl=en-US&origin=file%3A%2F%2F&url=http%3A%2F%2Fwww.mikelonsdale.co.uk%2F&ic=1&jsh=m%3B%2F_%2Fscs%2Fapps-static%2F_%2Fjs%2Fk%3Doz.gapi.en_GB.rtBP98PsisY.O%2Fm%3D__features__%2Fam%3DUQ%2Frt%3Dj%2Fd%3D1%2Frs%3DAItRSTPC6XpWJcUcEMEo2aHNHe_1oFgl3A#_methods=onPlusOne%2C_ready%2C_close%2C_open%2C_resizeMe%2C_renderstart%2Concircled%2Conload&id=I0_1405620467511&parent=file%3A%2F%2F&rpctoken=27602086

Error can't find file but it exists

[~/Sites/drees]
chris at CWB-MacBook $ grunt criticalcss:test
Running "criticalcss:test" (criticalcss) task

Something went wrong with phantomjs...
Fatal error: PHANTOM ERROR: Error: criticalCSS didn't run or no critical css, that seems unlikely
TRACE:
-> /Volumes/Vader/Users/chris/Sites/drees/node_modules/grunt-criticalcss/node_modules/criticalcss/lib/criticalrunner.js: 85
-> :/modules/webpage.js: 281PhantomJS has crashed. Please read the crash reporting guide at https://github.com/ariya/phantomjs/wiki/Crash-Reporting and file a bug report at https://github.com/ariya/phantomjs/issues/new with the crash dump file attached: /tmp/4527B703-39F4-414D-BB6A-56494AB41CB7.dmp

[~/Sites/drees]
chris at CWB-MacBook $ ls -lha /Volumes/Vader/Users/chris/Sites/drees/node_modules/grunt-criticalcss/node_modules/criticalcss/lib/
total 16
drwxr-xr-x 4 chris staff 136B Aug 11 19:12 .
drwxr-xr-x 14 chris staff 476B Aug 11 18:50 ..
-rw-r--r-- 1 chris staff 2.4K Aug 6 21:01 criticalcss.js
-rw-r--r-- 1 chris staff 2.2K Aug 11 18:55 criticalrunner.js

As you can see, the file criticalrunner.js exists in the path that the error said it didn't.

maxBuffer exceeded

When running the task, I'm running into an issue with phantomjs where I'm getting the following error:

Something went wrong with phantomjs...
Fatal error: stdout maxBuffer exceeded.

I noticed on the main CriticalCSS project, there's an options.buffer that lets you increase the maxBuffer, but not seeing anything about that in the docs on the grunt repo here.

Any plans to bring that over to here? Or is there another way to get around this error?

Phantomjs jQuery error

Hi,
I'm trying to use this on a drupal site I'm currently developing, but I'm getting the following error:

Fatal error: PHANTOM ERROR: ReferenceError: Can't find variable: jQuery
TRACE:

I'm not using jQuery on the site its self, but presume this isn't the problem?

Any ideas?

Shorthand CSS expands

It looks like criticalcss is expanding some properties when using shorthand css. For example,

background:url(image.jpg) 50% 0 no-repeat #fff;
-moz-background-size:cover;
-o-background-size:cover;
-webkit-background-size:cover;
background-size:cover;

becomes

background-image: url(image.jpg);
background-attachment: initial;
background-origin: initial;
background-clip: initial;
background-color: rgb(255, 255, 255);
-webkit-background-size: cover;
background-size: cover;
background-position: 50% 0px; 
background-repeat: no-repeat no-repeat;

I was just wondering if this was done on purpose, and if so, why.

Thanks!

Missing too many crucial rules

Hello -

Trying to get this to work with a WordPress theme for the agency I work for.

Trouble is, the generated CSS misses out so many rules that you get quite an ugly FOUC on load.

I've loaded the page without the non-critical CSS to show you what I mean. Our site is http://watb.co.uk.

Any help would be greatly appreciated. I currently have 89/100 mobile and 93/100 PS - I'd love to get this working. Practicality wise, our site is already extremely quick so it probably won't make much difference, but having this in the locker for client projects would be great.

criticalcss

embedded iframe breaks critical css generation?

EDIT: I thought that removing the iframe attributes fixed it, but I was mistaken

This is breaking the ccss output (it was not generating ccss for elements beyond this iframe)

<iframe src="https://www.google.com/maps/embed/v1/place?key=test&q=test"></iframe>

For now I have fixed it by commenting it out, generating critical css, and un-commenting... :(

ignoreConsole flag doesn't seem to work

I've set the ignoreConsole options flag to true, but I'm still seeing my task fail with the following error:

Something went wrong with phantomjs...
Fatal error: PHANTOM ERROR: Warning: It looks like you're using a minified copy of the development build of React. When deploying React apps to production, make sure to use the production build which skips development warnings and is faster. See https://fb.me/react-minification for more details.
TRACE:
 -> https://{our-url}/bundle.0d0f29608ee9b4bc15a9.js: 1 (in function e)

This is my current config:

criticalcss: {
	single : {
		options: {
			url: "https://{our-url}",
			width: 1200,
			height: 900,
			outputfile: get_destination_file( 'less', 'single', true ),
			filename: get_destination_file( 'less', 'app', true ),
			buffer: 8000*1024,
			ignoreConsole: true
		}
	},
},

Is there something wrong with this config? Any reason why ignoreConsole wouldn't be working? Thanks!

Copying extracted folder stuck because of PhantomJS

Downloading https://bitbucket.org/ariya/phantomjs/downloads/phantomjs-1.9.8-macosx.zip
Saving to /var/folders/rw/5lfpntc96k51n_dqkwx6_gln3hpdtt/T/phantomjs/phantomjs-1.9.8-macosx.zip
Receiving...
  [===========-----------------------------] 26% 0.0s
Received 9187K total.
Extracting zip contents
Removing /Applications/MAMP/htdocs/rolutex/web/theme/rolutex/node_modules/phantomjs/lib/phantom
Copying extracted folder /var/folders/rw/5lfpntc96k51n_dqkwx6_gln3hpdtt/T/phantomjs/phantomjs-1.9.8-macosx.zip-extract-1443086258120/phantomjs-1.9.8-macosx -> /Applications/MAMP/htdocs/rolutex/web/theme/rolutex/node_modules/phantomjs/lib/phantom

This is only happens if I include grunt-criticalcss. Without this module PhantomJS installs fine.
I'm guessing this is because i'm using npm 3.3.3 which shares modules instead of the old inception way of including modules.

Empty tags

Noticed an issue with the output .css file. The output .css include empty tags like:

@media (min-width: 64em){
    #primary-menu li{ }
    #primary-menu .sub-menu .sub-menu{ background-color: rgb(255, 255, 255); }
    #primary-menu a, .main-search input[type="search"]{ }
}

should be:

@media (min-width: 64em){
    #primary-menu li{ transition: background-color .3s ease, border-left-color .3s ease; }
    #primary-menu .sub-menu .sub-menu{ background-color: #fff; }
    #primary-menu a, .main-search input[type="search"]{ min-height: 8.33333vh; }
}

Warning about unsafe access from file URLs

I've noticed this before in my own generated CSS and noticed it again while peeking at https://filamentgroup.com to show an example of using this module:

Unsafe JavaScript attempt to access frame with URL about:blank from frame with URL file:///Users/scott/Sites/fgwebsite/node_modules/grunt-criticalcss/node_modules/criticalcss/lib/criticalrunner.js. Domains,protocols and ports must match.

I'm pretty sure this warning comes from PhantomJS: ariya/phantomjs#12697

PhantomJS Error : stdout maxBuffer exceeded

I have been trying to figure this out all day and can't seem to pinpoint the issue. I have a very long one page site. When I run the criticalcss grunt task, I get this error:

Running "criticalcss:home" (criticalcss) task
Something went wrong with phantomjs...
Fatal error: stdout maxBuffer exceeded.

When I run grunt -versions, I get:
grunt-cli v0.1.13
grunt v0.4.2

npm is at v2.14.3

Anyone running into this issue or how I can fix it? It's driving me crazy right now ha.

Thanks guys!

box-shadow

It seems that box-shadow is not processed correctly.

Input:

box-shadow: 0 1px 5px rgba(0, 0, 0, .2);

Output:

box-shadow: rgba(0, 0, 0, 0.199219) 0px 1px 5px;

PhantomJS dependency causing npm install to hang?

I have noticed the version of PhantomJS Critical CSS uses is 1.9.7, yet 1.9.8 and 2.0.0 are available.

Is this just me? I have cleared all global packages, and npm cache.

Once I remove Critical CSS from my package.json everything installs.

๐Ÿ˜‘

Node versions tried: 4.2.2, 5.0.0
NPM version 2.14.7
MAC OSX Yosemite 10.10.5

Module no longer installs

Since updating to latest NPM, the module no longer installs. It hangs at phantomjs install. Tested on 2 different machines.

โžœ  Netex git:(develop) โœ— npm install grunt-criticalcss   

> [email protected] install /Users/Zeno/Sites/Graffino/Box/Netex/node_modules/criticalcss/node_modules/phantomjs
> node install.js

Looks like an `npm install -g`; unable to check for already installed version.
Download already available at /var/folders/jg/dw8hwtn10cn8nyf25mr4yv700000gn/T/phantomjs/phantomjs-1.9.8-macosx.zip
Extracting zip contents
Removing /Users/Zeno/Sites/Graffino/Box/Netex/node_modules/criticalcss/node_modules/phantomjs/lib/phantom
Copying extracted folder /var/folders/jg/dw8hwtn10cn8nyf25mr4yv700000gn/T/phantomjs/phantomjs-1.9.8-macosx.zip-extract-1443018003805/phantomjs-1.9.8-macosx -> /Users/Zeno/Sites/Graffino/Box/Netex/node_modules/criticalcss/node_modules/phantomjs/lib/phantom

forceInclude has weird configuration

I'm using the latest version of grunt-criticalcss.

I found some weird behaviour with the forceInclude. I had to include a css selector with the cli of criticacss it looked like this:

node_modules/criticalcss/bin/critical.js -u https://domain.com -o foo.css -f bar.css  --force [.someSelector]

so I guessed that my grunt config should look like this

options: {
          forceInclude: ['.someSelector'],
          url: 'https://domain.com',
          filename: 'bar.css',
          outputfile: 'foo.css'
        }

But after debugging criticalcss used with grunt and CLI I figured out that to get the wanted behaviour (including .someSelector) I had to write the grunt config like this:

options: {
          forceInclude: ['[.someSelector]'],
          url: 'https://domain.com',
          filename: 'bar.css',
          outputfile: 'foo.css'
        }

Critical css & non-Critical css

If understand right, the script detects critical css and write it to new css file. What about non-critical css? Css that stays behind as a 'leftover'. Does non-critical-'below'-the-fold css can also somehow be generated, excluded and written in some file?

So one can put critical css in head or inline, and non-critical css in footer or load it defered with javascript.

Thanks, Rok

Allow multiple URLs in options.url

Since you don't know on which (sub)page a user will enter your site I think it might be useful to be able to specify a set of URLs to generate a critical.css from.

In case of a blog you might want to have something like

options: {
  url: [
    'http://my.blog.sexy/home.html',
    'http://my.blog.sexy/2015/03/11/sample-article.html'
  ]
}

That way a user always sees styled output no matter if he's landing on your homepage or coming via deeplink. Or do I get the idea of criticalcss wrong?

Sure, you could create multiple critical css files but I'm not sure if it is always useful to have 2-n 15k CSS files instead for each pagetype instead of a single critical css which might be a bit larger in filesize (maybe 20 or 25k).

Ability to use a URL as the filename

eg.
default: {
    options: {
        url: 'http://example.com',
        filename: 'http://example.com/assets/css/main.css',
        ...
    }
}

so that, after deployment, I wouldn't have to generate the styles again just to generate critical; I could just pull down the live styles.

Option to preserve property order

The issue I'm having is calc() and it's fallback swapping places. For example:

width: 50%;
width: calc(50% - 2em);

in all.css becomes:

width: calc(50% - 2em);
width: 50%;

in the generated critical CSS, causing a jump when all.css loads.

Is something like options.preservePropertyOrder possible?

Console output: [framesocket] timed out while pulling from persistent storage

Hello there.

Thanks you for great module ๐Ÿ‘

I hove some small problem. At the begin of output file present string:
Console output: [framesocket] timed out while pulling from persistent storage
And after this styles. Can you tell me please how to fix it?

Also in --verbose mode grunt says where is "no files":

Running "criticalcss:themeDesktopFunCritical" (criticalcss) task
Verifying property criticalcss.themeDesktopFunCritical exists in config...OK
File: [no files]
Options: width=960, height=900, outputfile="./skin/frontend/default/fun/build/css/styles-core.css", filename="./skin/frontend/default/fun/build/css/styles.css", url="http://fun.dev/", forceInclude=[], buffer=819200
Writing ./skin/frontend/default/fun/build/css/styles-core.css...OK
File "./skin/frontend/default/fun/build/css/styles-core.css" created.

But everything is looks like okay. Is it error or what?

Thanks

Specify project root in url ?

New to all this and using it for a couple of projects. Not an issue but a question.

So that I don't need to change the project url for each project can I somehow specify the project root in the url string with a variable?

It would be great if there is a way to check for the location of the Gruntfile.js and then go up to the project root and put that variable inside the url string for the task.

Can that be done somehow?
Below some pseudo code where you can see how I like to insert the project root.

index: {
  options: {
    url: "/",
    width: 1200,
    height: 900,
    outputfile: "resources/css/critical/critical-index.css",
    filename: "style.css"
  }
}
single: {
  options: {
    url: "/" + {projectRoot} + "/single/post/",
    width: 1200,
    height: 900,
    outputfile: "resources/css/critical/critical-single.css",
    filename: "style.css"
  }
},
"401": {
  options: {
    url: "/" + {projectRoot} + "/error-401/",
    width: 1200,
    height: 900,
    outputfile: "resources/css/critical/critical-401.css",
    filename: "style.css"
  }
},
"403": {
  options: {
    url: "/" + {projectRoot} + "/error-403/",
    width: 1200,
    height: 900,
    outputfile: "resources/css/critical/critical-403.css",
    filename: "style.css"
  }
},

My local projects are set up so that I have localhost/{ProjectName}/index.html etc. in the url and not via domain itself, though that should not matter for getting the project root I assume.

Thank you for any help with this.

Error: The filename you have given is not found at this url

Hi all,

I'm having a lot of trouble getting this to work. I have tried absolute URLs, relative URLs, removing inline JS from <head> and each time I get:

Fatal error: PHANTOM ERROR: Error: The filename you have given is not found at this url.

My Gruntfile has:

criticalcss: {
    custom_options: {
        options: {
            url: "192.168.10.144:8005",
            width: 1200,
            height: 900,
            outputfile: "dist/css/critical.css",
            filename: "dist/css/tpl-home.css"
        }
    }
}

I'm stumped, any help would be greatly appreciated.

Module no longer installs - phantomjs

Since updating to latest NPM, the module no longer installs. It hangs at phantomjs install.
(npm: 4.2.0, node: v6.0.0):

$ npm update
npm WARN deprecated [email protected]: wrench.js is deprecated! You should check out fs-extra (https://github.com/jprichardson/node-fs-extra) for any operations you were using wrench for. Thanks for all the usage over the years.
npm WARN deprecated [email protected]: graceful-fs v3.0.0 and before will fail on node releases >= v7.0. Please update to graceful-fs@^4.0.0 as soon as possible. Use 'npm ls graceful-fs' to find it in the tree.
npm WARN deprecated [email protected]: use uuid module instead
npm WARN deprecated [email protected]: Please update to minimatch 3.0.2 or higher to avoid a RegExp DoS issue
npm WARN deprecated [email protected]: ReDoS vulnerability parsing Set-Cookie https://nodesecurity.io/advisories/130
npm WARN deprecated [email protected]: this package has been reintegrated into npm and is now out of date with respect to npm
npm WARN deprecated [email protected]: graceful-fs v3.0.0 and before will fail on node releases >= v7.0. Please update to graceful-fs@^4.0.0 as soon as possible. Use 'npm ls graceful-fs' to find it in the tree.
npm WARN deprecated [email protected]: Please update to minimatch 3.0.2 or higher to avoid a RegExp DoS issue
npm WARN deprecated [email protected]: Please update to minimatch 3.0.2 or higher to avoid a RegExp DoS issue
npm WARN deprecated [email protected]: graceful-fs v3.0.0 and before will fail on node releases >= v7.0. Please update to graceful-fs@^4.0.0 as soon as possible. Use 'npm ls graceful-fs' to find it in the tree.
npm WARN deprecated [email protected]: Please update to minimatch 3.0.2 or higher to avoid a RegExp DoS issue
npm WARN deprecated [email protected]: this package has been reintegrated into npm and is now out of date with respect to npm
npm WARN deprecated [email protected]: the module is now available as 'css-select'
npm WARN deprecated [email protected]: the module is now available as 'css-what'
npm WARN deprecated [email protected]: ReDoS vulnerability parsing Set-Cookie https://nodesecurity.io/advisories/130
npm WARN deprecated [email protected]: use cross-spawn or cross-spawn-async instead.
npm WARN prefer global [email protected] should be installed with -g
npm WARN prefer global [email protected] should be installed with -g
npm WARN prefer global [email protected] should be installed with -g
npm WARN prefer global [email protected] should be installed with -g

[email protected] install /Users/aa/Desktop/working files/rmhc/node_modules/phantomjs
node install.js
Download already available at /var/folders/9h/515hzz4j7xb8_jsf18yfn1jj60m4p3/T/phantomjs/phantomjs-1.9.8-macosx.zip
Extracting zip contents
Removing /Users/aa/Desktop/working files/rmhc/node_modules/phantomjs/lib/phantom
Copying extracted folder /var/folders/9h/515hzz4j7xb8_jsf18yfn1jj60m4p3/T/phantomjs/phantomjs-1.9.8-macosx.zip-extract-1487705220034/phantomjs-1.9.8-macosx -> /Users/aa/Desktop/working files/rmhc/node_modules/phantomjs/lib/phantom

:before and :after pseudo selectors

It appears that before or after pseudo selectors won't be read if you use single colons (e.g. :before and :after instead of ::before and ::after). I tried adding single colon selectors in the forceInclude and it also wouldn't take unless I made it a double colon.

I realize that double colons are the preferred syntax moving forward, so I'm going to update my code in the mean time. However, I know I'm still in the habit of writing them with single colons and assuming some folks will still need to support IE8, so it might be a good idea to allow them.

Bootstrap 3.0 - Glyphicons causing - Unexpected end of input

Hello, I was having issues getting the critical CSS outputted and started pruning the CSS file down to see if I could find the culprit. It turns out that this was it:

.glyphicon-file:before {
    content: "\e022";
}

Does that ring a bell with you? I changed the selector's name to .glyphicon-files and it worked just fine. So it appears the word 'file' in the selector freaked things out.

Multiple Critical CSS files - Home / Inner

I would love to see an example in the documentation of a multiple file setup. A good example could show a Home page and Inner page setup. Often times home styles differ from an inner template.

Is there configuration for multiple templates? I tried messing with arrays but didn't seem to work eg.

options: {
    url: ["http://localhost:4000,"http://localhost:4000/inner-page"],
    width: 1200,
    height: 900,
    outputfile: ["/path/to/local/home.css","/path/to/local/inner.css"],
    filename: config.compiledCss,
    buffer: 800*1024
}

Maybe this could just be handled creatively in Grunt? Currently I'm just switching manually. I'm not even sure if this is optimal..might take a while on build.

How do you suggest we handle this situation?

vh ( and probably vw ) support

Hey,
For some reason compiler doesn't want to add vh to critical.css. But if you change vh to pixels or something else - it works as expected. I even tried remove all styles from selector and leave only height:100vh (100.0vh) and add to to forceInclude array but it didn't help.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.