Giter Club home page Giter Club logo

prerender-chrome-headless's Introduction

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

prerender-chrome-headless's People

Contributors

anishkny avatar brinley avatar dependabot[bot] avatar piuccio 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

Watchers

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

prerender-chrome-headless's Issues

adding inline stylesheet and javascript?

Hey,

first of all, great work! Everything works like expected.
What do you think about adding this lines to your plugin?
To inline the Stylesheets and the JavaScript files.

first

const urlModule = require('url');
const URL = urlModule.URL;

underneath
const delayPageLoad,
const puppeteerOptions etc...

const stylesheetContents = {};
const javascriptContents = {};

the first part of your chain() function behind (page) => page.on('pageerror', ...

`stash stylesheet and javascript`,
(page) => page.on('response', async resp => {
        const responseUrl = resp.url();
        const sameOrigin = new URL(responseUrl).origin === new URL(source).origin;
        const isStylesheet = resp.request().resourceType() === 'stylesheet';
        const isJavaScript = resp.request().resourceType() === 'script';
        if (sameOrigin && isStylesheet) {
            stylesheetContents[responseUrl] = await resp.text();
        }
        if (sameOrigin && isJavaScript) {
            javascriptContents[responseUrl] = await resp.text();
        }
    }),

the second part in .then(([browser, page]) => chain(...
behind () => page.waitFor(delayPageLoad),...

`inline stylesheet`,
() => page.$$eval('link[rel="stylesheet"]', (links, content) => {
        links.forEach(link => {
            const ctx = content[link.href];
            if (ctx) {
                const style = document.createElement('style');
                style.textContent = ctx;
                link.replaceWith(style);
            }
        });
    }, stylesheetContents),

`inline javascript`,
() => page.$$eval('script[type="text/javascript"]', (links, content) => {
        links.forEach(link => {
            const ctx = content[link.src];
            if (ctx) {
                const script = document.createElement('script');
                script.textContent = ctx;
                link.replaceWith(script);
            }
        });
    }, javascriptContents),

Let me know about your thoughts :)

cheers

Possible to include delay or timeout? SPA not rendered before captured.

Your stock application doesn't work for my react-static-boilerplate based SPA. React hasn't rendered the page when loadEventFired() has returned. If I add a delay in your index.js, then react has time to render inside of chrome:

  () => debug('Waiting for page load event to be fired'),
  () => Page.loadEventFired(),
  () => { var r; let p= new Promise((resolve,reject) => r = resolve); setTimeout(()=> r(),3000); return p },

Is there an event that specifies that the SPA has rendered or can you add a delay option for the user?

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.