When we create our visualizations, we need to first load the D3 library and the CSS styles that we want to apply. For each of the samples, we'll use the following basic HTML skeleton:
<html>
<head>
<!-- generic stuff -->
<script src="../libs/d3.js"></script>
<script src="../libs/lodash.js"></script>
<link rel="stylesheet" href="../css/default.css">
<!-- specific stuff -->
<script src="./js/D01-01.js"></script>
<link rel="stylesheet" href="./css/D01-01.css" type="text/css">
</head>
<body>
<div id="output">
<svg class="chart"></svg>
</div>
<script>
(function() {
show();
})();
</script>
</body>
</html>
This is a standard HTML page, where we first load the complete D3 sources (./libs/d3/js), the lodash JavaScript library, and CSS styles (../css/default.css) that we want to apply to all the examples in this book. We also load the example specific JavaScript (in this example, ./js/D01-01.js) and the example specific CSS (./css/D01-01.css). In this page, we also define a single div tag that has an id with a value output. This is the location in the page where we add our visualizations. A quick note on lodash. Lodash provides a large set of useful collection-related functions, which makes creating and working with JavaScript arrays a lot more convenient. You can see when we use a lodash function when the function call starts with an underscore: for example, _.range(2010, 2016).
There are different ways to load the D3 libraries. In our examples, we load the complete D3 library as a single JavaScript file (the <script src="../libs/d3.js"></script> import). This will load all the APIs provided by D3. D3, however, also comes in a set of micro-libraries, where each library provides a standalone piece of functionality. You can use this to limit the size of the required JavaScript by only including the APIs you need.
Once the page is loaded, the following code block runs, which calls the show function which we'll implement in the example specific JavaScript (./js/D01-01.js in this case):
<script>
(function() {
show();
})();
</script>
The show function implementation will differ for each example, but this way we can keep the basic skeleton the same, and we can focus on JavaScript and the D3 APIs. Note that in this book, we won't explain in detail the JavaScript concepts we use. If you need a reminder on how anonymous functions, closures, variable scope, and so on, work in JavaScript, a great resource is the Mozilla Developer Network (MDN) page on JavaScript: https://developer.mozilla.org/en-US/docs/Web/JavaScript.