Skip to content

Pre-render single page applications to static HTML file

License

Notifications You must be signed in to change notification settings

piuccio/prerender-chrome-headless

Repository files navigation

Build Status

Generate static pages from single page applications

Few tool out there allow you to pre-render web applications to static pages either using webpack or fake browser.

This package uses headless chrome for a more accurate pre-rendering in an actual browser.

As of version 2.0.0 this package internally uses puppeteer.

Usage

const render = require('prerender-chrome-headless');
const fs = require('fs');

render('https://google.com').then((html) => {
  fs.writeFileSync('/tmp/rendered-page.html', html);
});

Chrome flags

By default this package runs chrome with --disable-gpu and --headless you can pass additional flags calling

render(url, ['--disable-http2'])

Options

render(url, {
  delayLaunch: 0, // milliseconds
  delayPageLoad: 0, // milliseconds
  chromeFlags: [], // list of flags
  puppeteerOptions: {}, // puppeteer launch options
  onPageError() {} // callback
});

The second parameter of render function can either be an array of chrome flags or an object with

  • delayLaunch Wait to launch Chrome browser, in case you need more time to set up the server
  • delayPageLoad Wait after the page load event for your JS to run
  • chromeFlags List of chrome flags
  • puppeteerOptions Options for puppeteer launch as documented at puppeteer. Note, you can specify chromeFlags here as well but if you specified chromeFlags then that takes precedence over args defined in puppeteerOptions.
  • onPageError Function called when an uncaught exception happens within the page. You can use this function for instance to fail your build if error happens during the generation of the page

Continuous integration

The package works on any machine with Chrome installed. Most CI environments allows you to install external packages.

Travis

Here is what you have to do to get Chrome headless working on Travis

# The default at the time of writing this blog post is Ubuntu `precise`
# Chrome addon is only available on trusty+ or OSX
dist: trusty

# This will install Chrome stable (which already supports headless)
addons:
  chrome: stable

before_install:
  # Needed by `chrome-launcher`
  - export LIGHTHOUSE_CHROMIUM_PATH=google-chrome-stable

script:
  # Run your build script that fetches a page and writes the output
  - node generate_static_page.js

Related links