• Stars
    star
    285
  • Rank 145,115 (Top 3 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created almost 11 years ago
  • Updated almost 8 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Grunt plugin wrapping phantomas to measure frontend performance

grunt-phantomas

Build Status bnpm version npm downloads Dependency Status Coverage Status Built with Grunt

Grunt plugin for phantomas

Maintainers Wanted

Getting Started

This plugin requires Grunt ~0.4.1

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-phantomas --save-dev

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

grunt.loadNpmTasks('grunt-phantomas');

The "phantomas" task

You're looking for a tool that gives you detailed metrics about your site? Great!!! This grunt plugin executes phantomas for you and visualizes the returned metrics in a generated index.html for you. It will keep track of history, so that you can set it up and check reports after every deployment of your site. Read below to learn how to setup history tracking in different CI systems.

Examples of rendered output:

I'm still at early stage, but I think you can already work with it. ;)

Overview

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

grunt.initConfig( {
  phantomas: {
    gruntSite : {
      options : {
        indexPath : './phantomas/',
        options   : {},
        url       : 'http://gruntjs.com/',
        buildUi   : true
      }
    }
  }
} )

Options

options.additionalStylesheet

Type: String|Boolean Default value: false

If you don't like the phantomas default styling and want to customize it, you can set the path to an additional stylesheet, that will be copied and loaded in the generated index.html.

options.assertions

Type: Object Default Value: {}

An object that represents possible assertions for your generated UI. Best way is to run grunt-phantomas once and setting these values afterwards for particular metrics. The UI will warn you whenever the median value of your defined runs of a specific metric will go over the specified value by highlighting depending graphs and showing warnings on top of the built UI. Using this option you can easily keep track of getting worse values. Performance budget for the win. :)

Example:

phantomas : {
  /* https://github.com/stefanjudis/grunt-phantomas */
  grunt : {
    options : {
      assertions : {
        assetsWithQueryString : 3,     // receive warning, when there are more than 3 assets with a query string
        bodyHTMLSize          : 10500, // receive warning, when the bodyHTMLsize is bigger than 10500
        jsErrors              : 0,     // receive warning, when more than 0 JS errors appear
        gzipRequests          : {      // receive warning, when less compressed assets are loaded then 10 ( might be useful for checking server configurations )
          type  : '<',
          value : 10
        }
      },
      indexPath  : './phantomas/',
      options    : {
        'timeout' : 30
      },
      url        : 'http://gruntjs.com/'
    }
  }
}

options.buildUi

Type: Boolean Default value: true

If you want to use grunt-phantomas without generating a UI for the data, this is an option to switch off the visualization interface. If set to false only defined data format will be outputted at options.indexPath + '/data/'.

options.indexPath

Type: String Default value: ./phantomas/

A string value that represents the relative path to the place where phantomas will render your metrics. Inside of this folder an index.html, a data folder and an assets folder will be created.

options.limitIncludedRuns

Type: Number|false Default value: 30

A numeric value that sets a limit for the included runs inside of the built UI. In case you run grunt-phantomas on a hourly/daily basis the generated UI might become slow, because of the big amout of data. Solve this by setting the limit to a lower value.

In case you are fine with all runs included in the UI set it to false.

options.numberOfRuns

Type: Number Default value: 5

A numeric value that represents the number of times the phantomas executable will be started. The more times it runs the more reliable metrics become.

options.options

Type: Object Default value: {}

An object that represents possible options for phantomas executable. For more information please check the official api documentation and list of possible parameters. See usage examples later on.

options.output

Type: Array Default value: [ 'json', 'csv' ]

Choose to output CSV or JSON files. The default is JSON and CSV. The buildUi option does not work if json is not included in options.output. You have to set buildUi to false, if you want to write CSV files only.

options.group

Type: Object Default value:

{
  'REQUESTS' : [
    'requests',
    'gzipRequests',
    'postRequests',
    'httpsRequests',
    'notFound',
    'multipleRequests',
    'maxRequestsPerDomain',
    'domains',
    'medianRequestsPerDomain',
    'redirects',
    'redirectsTime',
    'smallestResponse',
    'biggestResponse',
    'smallestLatency',
    'biggestLatency',
    'medianResponse',
    'medianLatency',
    'assetsNotGzipped',
    'assetsWithQueryString',
    'smallImages'
  ],
  'TIMINGS' : [
    'timeToFirstByte',
    'timeToLastByte',
    'timeToFirstCss',
    'timeToFirstJs',
    'timeToFirstImage',
    'fastestResponse',
    'slowestResponse',
    'onDOMReadyTime',
    'onDOMReadyTimeEnd',
    'windowOnLoadTime',
    'windowOnLoadTimeEnd',
    'httpTrafficCompleted',
    'timeBackend',
    'timeFrontend'
  ],
  'HTML' : [
    'bodyHTMLSize',
    'iframesCount',
    'imagesWithoutDimensions',
    'commentsSize',
    'hiddenContentSize',
    'whiteSpacesSize',
    'DOMelementsCount',
    'DOMelementMaxDepth',
    'nodesWithInlineCSS',
    'foo'
  ],
  'JAVASCRIPT' : [
    'eventsBound',
    'documentWriteCalls',
    'evalCalls',
    'jsErrors',
    'consoleMessages',
    'windowAlerts',
    'windowConfirms',
    'windowPrompts',
    'globalVariables',
    'localStorageEntries',
    'ajaxRequests'
  ],
  'DOM' : [
    'DOMqueries',
    'DOMqueriesById',
    'DOMqueriesByClassName',
    'DOMqueriesByTagName',
    'DOMqueriesByQuerySelectorAll',
    'DOMinserts',
    'DOMqueriesDuplicated'
  ],
  'HEADERS' : [
    'headersCount',
    'headersSentCount',
    'headersRecvCount',
    'headersSize',
    'headersSentSize',
    'headersRecvSize'
  ],
  'CACHING' : [
    'cacheHits',
    'cacheMisses',
    'cachePasses',
    'cachingNotSpecified',
    'cachingTooShort',
    'cachingDisabled'
  ],
  'COOKIES' : [
    'cookiesSent',
    'cookiesRecv',
    'domainsWithCookies',
    'documentCookiesLength',
    'documentCookiesCount'
  ],
  'COUNTS & SIZES' : [
    'contentLength',
    'bodySize',
    'htmlSize',
    'htmlCount',
    'cssSize',
    'cssCount',
    'jsSize',
    'jsCount',
    'jsonSize',
    'jsonCount',
    'imageSize',
    'imageCount',
    'webfontSize',
    'webfontCount',
    'base64Size',
    'base64Count',
    'otherCount',
    'otherSize'
  ],
  'JQUERY' : [
    'jQueryOnDOMReadyFunctions',
    'jQuerySizzleCalls'
  ]
}

An object that represents the metrics grouping rendered inside of the generated index.html. You can set up your grouping by just passing another object to this option.

Example:

phantomas : {
  /* https://github.com/stefanjudis/grunt-phantomas */
  grunt : {
    options : {
      indexPath : './phantomas/',
      options   : {
        'timeout' : 30
      },
      url       : 'http://gruntjs.com/',
      group     : {
        'foo' : [ 'cookiesSent' ]
      }
    }
  }
}

This configuration will lead to a rather empty looking rendered index.html. :) Additionally you will be informed, which metrics you missed during the build process.

Output for example:

CHECKING FOR NOT DISPLAYED METRICS.
>> You are currently not displaying the following metrics:
>> requests, gzipRequests, postRequests, httpsRequests, notFound, timeToFirstByte, timeToLastByte, bodySize, contentLength, ajaxRequests, htmlCount, htmlSize, cssCount, cssSize, jsCount, jsSize, jsonCount, jsonSize, imageCount, imageSize, webfontCount, webfontSize, base64Count, base64Size, otherCount, otherSize, cacheHits, cacheMisses, cachePasses, cachingNotSpecified, cachingTooShort, cachingDisabled, consoleMessages, domains, maxRequestsPerDomain, medianRequestsPerDomain, DOMqueries, DOMqueriesById, DOMqueriesByClassName, DOMqueriesByTagName, DOMqueriesByQuerySelectorAll, DOMinserts, DOMqueriesDuplicated, eventsBound, headersCount, headersSentCount, headersRecvCount, headersSize, headersSentSize, headersRecvSize, documentWriteCalls, evalCalls, jQueryOnDOMReadyFunctions, jQuerySizzleCalls, jsErrors, redirects, redirectsTime, assetsNotGzipped, assetsWithQueryString, smallImages, multipleRequests, timeToFirstCss, timeToFirstJs, timeToFirstImage, onDOMReadyTime, onDOMReadyTimeEnd, windowOnLoadTime, windowOnLoadTimeEnd, timeBackend, timeFrontend, httpTrafficCompleted, windowAlerts, windowConfirms, windowPrompts, cookiesRecv, domainsWithCookies, documentCookiesLength, documentCookiesCount, bodyHTMLSize, iframesCount, imagesWithoutDimensions, commentsSize, hiddenContentSize, whiteSpacesSize, DOMelementsCount, DOMelementMaxDepth, nodesWithInlineCSS, globalVariables, localStorageEntries, smallestResponse, biggestResponse, fastestResponse, slowestResponse, smallestLatency, biggestLatency, medianResponse, medianLatency

options.url

Type: String Default value: http://gruntjs.com/

A string value that represents the url of the site, which will be analyzed by phantomas.

Usage Examples

Default Options

In this example, the default options are used to fetch metrics of http://gruntjs.com and render the visualized metrics at ./phantomas.

grunt.initConfig({
  phantomas: {
  	yourSite: {}
  }
});

Grunt task options

In this example, custom options are used to fetch metrics of http://yoursite.com and render the visualized metrics at ./yoursite/.

grunt.initConfig( {
  phantomas: {
    yourSite : {
      options : {
        additionalStylesheet : '/Users/foo/bar/custom.css',
        assertions : {
          'assetsWithQueryString' : 3,
          'biggestLatency'        : 1400,
          'bodyHTMLSize'          : 10500,
          'commentsSize'          : 55,
          'consoleMessages'       : 0,
          'hiddenContentSize'     : 65,
          'jsErrors'              : 0,
          'gzipRequests'          : 8,
          'medianResponse'        : 400,
          'nodesWithInlineCSS'    : 0,
          'requests'              : 30,
          'timeToFirstImage'      : 1100,
          'DOMelementsCount'      : 200,
          'DOMqueries'            : 10
        },
        indexPath            : './yoursite/',
        url                  : 'http://yoursite.com/',
        numberOfRuns         : 10
      }
    }
  }
} );

Output options

Build ui
grunt.initConfig( {
  phantomas: {
    yoursite : {
      options : {
        indexPath            : './phantomas/',
        options              : {
          'timeout' : 30
        },
        url                  : 'http://gruntjs.com/'
      }
    }
  }
}
Export JSON data only
grunt.initConfig( {
  phantomas: {
    yoursite : {
      options : {
        buildUi              : false,
        output               : 'json',
        indexPath            : './phantomas/',
        options              : {
          'timeout' : 30
        },
        url                  : 'http://gruntjs.com/'
      }
    }
  }
}
Export CSV data only
grunt.initConfig( {
  phantomas: {
    yoursite : {
      options : {
        buildUi              : false,
        output               : 'csv',
        indexPath            : './phantomas/',
        options              : {
          'timeout' : 30
        },
        url                  : 'http://gruntjs.com/'
      }
    }
  }
}

Phantomas options

In this example, the phantomas option is used to set phantomas execution parameters. In this case all external script except the defined ones are blocked by phantomas, what can become really handy, when dealing with a lot of third party scripts that influence your site performance. Additionally phantomas will wait 30 seconds for all resources to be loaded until it quits with the timeout status code 252.

grunt.initConfig( {
  phantomas: {
    yourSite : {
      options : {
        indexPath : './yoursite/',
        options   : {
          'allow-domain' : 'cdn.yoursite.com.br,ajax.googleapis.com',
          'no-externals' : true,
          'timeout'      : 30

        },
        url       : 'http://yoursite.com'
      }
    }
  }
} );

Troubleshooting

By default, the experimental film-strip option is true. If the grunt phantomas command fails, try setting the film strip option to false:

grunt.initConfig( {
  phantomas: {
    yourSite : {
      options : {
        indexPath : './yoursite/',
        options   : {
          'film-strip'   : false
        },
        url       : 'http://yoursite.com'
      }
    }
  }
} );

Tracking history in CI

To track history in Travis CI, use the caching option to cache the indexPath folder.

Note:

Formatters are not supported as options for Phantomas, because they are not implemented in the CommonJS version of Phantomas.

Donating

Support this project and others by stefanjudis via gittip.

Support via Gittip

Contributing

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

To make sure tests are passing and coding style is in a good shape please run grunt test before applying changes.

Release History

Please check release history at Github. :)

More Repositories

1

tiny-helpers

A collection of useful online web development tools
JavaScript
930
star
2

perf-tooling

List of performance analysis, monitoring and optimization tools
JavaScript
644
star
3

grunt-photobox

Grunt plugin for creating screenshots of any site and compare them
Smarty
277
star
4

awesome-command-palette

A list of awesome command palette implementations.
195
star
5

credits-cli

Find out on whose work your project is based on
JavaScript
193
star
6

dotfiles

The setup I run on every computer
Shell
189
star
7

sparkly-text

A small web component for making your text spark.
JavaScript
179
star
8

web-vitals-element

A custom element to display web vitals metrics on your page.
JavaScript
172
star
9

netlify-menubar

Netlify menubar app to receive build information or trigger new builds
TypeScript
153
star
10

css-scroll-shadows

Website to quickly create CSS scroll shadows
JavaScript
139
star
11

is-http2-cli

CLI Module to check for http/2 support
JavaScript
51
star
12

browsers.fyi

Get browser versions as website or abpi
Nunjucks
31
star
13

sketch-contentful

A Sketch App plugin to populate your documents with data stored in Contentful.
JavaScript
28
star
14

create-phone-number-forwarding

A CLI tool to quickly buy a Twilio phone number and forward calls/SMS to another number
Shell
24
star
15

grunt-jsinspect

Grunt task for jsinspect
JavaScript
22
star
16

designMode-chrome-extension

Chrome extension to easily use document.designMode
JavaScript
22
star
17

github-light-dark-image-example

22
star
18

1-1-question-now

A quick app that gives you a question to ask in your one to one
JavaScript
21
star
19

just-write-a-fn

Example React app using netlify functions to send emails
JavaScript
20
star
20

tiny-teachers

A collection of online learning tools and courses for web developers.
Nunjucks
13
star
21

blocky

Application (Win/MacOS) to block screensaver and sleep mode easily
JavaScript
10
star
22

credits

Find out on whose work your project is based on
JavaScript
10
star
23

8-bit-revolution

Tell your friends how much you like 8-bit
JavaScript
9
star
24

caniuse-embed-element

JavaScript
8
star
25

extract-media

A command line utility to extract media from .key and .docx files
JavaScript
8
star
26

stefanjudis

HTML
8
star
27

mdx-contentful-ui-extension

Contentful UI extension to preview MDX
JavaScript
7
star
28

cushion-cli

The command line tool to control your CouchDB.
JavaScript
7
star
29

contentful-enriched-markdown

JavaScript
6
star
30

contentful-analytics-ui-extension

Embed Google Analytics in the Contentful UI
HTML
6
star
31

react-in-a-worker

Example of React running in the client, a service worker and cloudflare worker
JavaScript
6
star
32

pwt-workshop

A Playwright Test workshop
JavaScript
6
star
33

har-diff

Tool to get diff statistics of two har-files
JavaScript
5
star
34

travalizit-app

Web App to analysize travis build data.
JavaScript
5
star
35

alex-js-contentful-ui-extension

A Contentful UI extension to check for insensitive writing
HTML
5
star
36

contentful-link-checker-ui-extension

A UI extension to check for broken or invalid links
HTML
5
star
37

webComponents-tutorial

Example page for implementing web components via polymer.js
CSS
5
star
38

phantomas-ui

Create visually appealing dashboards with data gathered by phantomas
JavaScript
5
star
39

covery

JavaScript
4
star
40

today-i-learned

Example application of a universal React app running with Contentful on Netlify
JavaScript
4
star
41

contentful-graphql-course

JavaScript
4
star
42

npm-package-to-env

Load package.json data and make them accessible via process.env
JavaScript
4
star
43

a-better-contentful-home-dashboard

TypeScript
3
star
44

twilio-workshop

Twilio Workshop for Chat, Video and WhatsApp
JavaScript
3
star
45

create-module

Boilerplate for new Node.js projects
Shell
3
star
46

gatsby-starter-contentful-knowledge-base

JavaScript
3
star
47

confetti-element

JavaScript
3
star
48

pwt-workshop-solutions

TypeScript
3
star
49

electron-podcast

Example how to build a webview app
JavaScript
3
star
50

photobox

Module to create screenshots of your site and check if the layout has changed
JavaScript
3
star
51

jamstack-workshop

JavaScript
3
star
52

serverless-contentful-watermark

A serverless function to create Contentful images with watermarks
JavaScript
3
star
53

stefan-judis-website-editors

Contentful editors for my own site
JavaScript
3
star
54

podbot-functions

How to control Twilio voice calls with Serverless functions
JavaScript
3
star
55

jamstack-workshop-start

The beginning of the Jamstack Conf Next.js/Contentful workshop
JavaScript
3
star
56

electron-patch-fs

Monkey patch electrons fs functions with the original ones
JavaScript
3
star
57

webperf-101-workshop-final

Final material for the web performance workshop
JavaScript
2
star
58

alice-app

JavaScript
2
star
59

bouncer

Tool to evaluate impact of 3rd party script
JavaScript
2
star
60

github-actions-profile-readme-example

Example showing how to render a GitHub profile README including Contentful data with GitHub actions
JavaScript
2
star
61

phantomjs-screenshot

Script to make screenshots of a given site
JavaScript
2
star
62

webperf-101-workshop

Material for the web performance workshop
JavaScript
2
star
63

twilio-serverless-sms-group-chat

JavaScript
2
star
64

code-examples

2
star
65

electron-block-screensaver-example

Example project for Electron show off
JavaScript
2
star
66

stefan-judis-about

about.me clone
HTML
1
star
67

alice-generator

JavaScript
1
star
68

my-links-online

Serverless URL shortener using Contentful
JavaScript
1
star
69

the-responsible-developer

HTML
1
star
70

today-i-learned-dev

JavaScript
1
star
71

alfred-weigh

Alfred workflow to get bundles sizes using weigh
JavaScript
1
star
72

sync-tryout

Just testing stuff.
JavaScript
1
star
73

helen

CLI tool for har-diff report generation
JavaScript
1
star
74

bouncer-proxy

Proxy server to block certain requests via CSP
JavaScript
1
star
75

travalizit

Node.js Travis API
JavaScript
1
star
76

today-i-learned-spa

Example application of a React app running with Contentful on Netlify
JavaScript
1
star
77

hide-twitter-follower-extension

1
star
78

a-site-without-a-file-to-my-computer

Created with CodeSandbox
HTML
1
star
79

pw-fixtures

JavaScript
1
star
80

a-checkly-gh-sync-example

Example for Checkly Launch Week
JavaScript
1
star
81

contentful-usage-checker

Chrome extension to see which sites run on Contentful
JavaScript
1
star
82

a-picture-a-day

PWA to see yourself getting older taking a picture a day
1
star
83

phantomas-custom-metrics-tryout

Tryout page to show of phantomas custom metrics
CSS
1
star
84

guardcat

A utility to help you keep track of github notifications
JavaScript
1
star
85

animated-svg-favicon

Test to animate an SVG favicon
HTML
1
star
86

download-it-now

Serverless proxy function to trigger a download
1
star