liveBook · Manning

Script element

As explained in D3.js in Action, Third Edition

A script element, or script tag, is an HTML element that embeds executable code or references an external script file.

A script element embeds executable JavaScript or references an external file. In an HTML page, it can load the D3 library and the application code that produces a visualization. section 2.2.2

Use script elements with these practical rules:

  • Place them just before the closing body tag so the DOM is available before scripts manipulate it and the page can display sooner. section 2.2.2
  • List dependencies before the code that uses them; load D3 before main.js or the browser will report errors and stop execution. section 2.2.2
  • Choose between linking a complete library, loading selected D3 modules, or using NPM modules for framework-based projects. section 2.2.2 section 2.7

Load D3 before application code

Add the D3 library first, then the project file: <script src="https://d3js.org/d3.v7.min.js"></script> followed by <script src="js/main.js"></script>. Code in main.js can then call D3 methods such as d3.select(). section 2.2.2 section 2.7

Listing 2.1 Loading the entire D3 library in a script tag: index.html
<!DOCTYPE html>
<html>
<head> ... </head>
<body>
  <div class="container">
    <h1>You are about to start working with D3!</h1>
  </div>

  <script src="https://d3js.org/d3.v7.min.js"></script>  #1

  <script src="js/main.js"></script>  #2

</body>  #3
</html>

Inspect a complete index.html example showing the script elements, their order, and their position before </body>. section 2.2.2

How D3.js in Action, Third Edition covers it

How deep it goes
Explains external loading, dependency order, placement, and module alternatives, but not script-element parsing internals.
Examples
Uses D3 v7, main.js, index.html, d3.select(), and a title whose color changes through D3.
What it assumes
Assumes an HTML project and local web server, while introducing D3 loading and DOM access progressively.
What you can do after
Operate/configure HTML files to load D3 before JavaScript that depends on it.
How it connects
Connects HTML, JavaScript, the DOM, D3, NPM modules, and CSS selectors.

Also explained in

Compare how 3 books explain script element →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of D3.js in Action, Third Edition. The section links point to the parts of the book it draws on.