The pre-rendering tool uses a headless browser to turn d3 code into its resulting SVG, and inserts the markup into your HTML. Then, the
d3.append to check if a pre-rendered DOM node already exists before creating a new one. This approach allows you to use pre-rendered SVG without changing your visualization code.
In the wild
npm install --save d3-pre
There are two things that you need to do to use this library:
var d3 = ;// Require the library and give it a reference to d3var Prerender = ;var prerender = ;// Then, when you start drawing SVG, call `prerender.start()`.// This modifies some d3 functions to make it aware// of the pre-rendered SVGs.prerenderstart;/** Existing d3 code goes here* d3.select('body')* .append('svg')* .data(data)* .enter()* .append('rect')* .on('click', clickhandler)* etc. etc.*/// If you ever want to go back to the unmodified d3,// just call `prerender.stop()`.// This is optional and usually not necessary.prerender;
2. Pass your HTML through the pre-rendering tool.
This can be done via a build task (like gulp), or on the command line. To provide control over which DOM modifications are saved back to the HTML file, you can add the following data-attributes in the HTML:
data-prerender-ignore: Any modifications that happen inside a node with this attribute will be ignored.
data-prerender-only: Only modifications inside of this node are saved.
data-prerender-minify: Any SVG with this attribute will automatically be passed through an SVG minification tool.
Command line example
Install the command line tool:
$ npm install -g d3-pre-cli
d3-pre command on an HTML file:
$ d3-pre ./path/to/index.html
Install the gulp plugin:
$ npm install gulp-d3-pre
Create a gulp task:
var gulp = ;var d3Pre = ;gulp
preprocessHTML- A function to run before running the HTML through the pre-renderer. Takes a string as input and expects a string as output.
postprocessHTML- A function to run after running the HTML through the pre-renderer. Takes a string as input and expects a string as output.
Both of the above modules are thin wrappers around d3-pre-renderer. If you require more fine-grained control of when and where the pre-rendering step takes place, use d3-pre-renderer directly.
- Adds support for d3