Loading data

Quite often, you won't have the benefit of being able to create data using the Math random number generator functions, you'll need to load it from an external source. While sometimes it's easier to have your code generate your dataset, most of the time you'll be mapping real data to what you create with D3.

You can get data in a number of ways. I'll cover the main ones here:

  • Make some sort of manual HTTP request: We already did this in earlier chapters. We supply a URL to a function that causes the browser to make a request. Both XMLHttpRequest and Fetch fall into this category. To import JSON, the server needs to have Cross-Origin Resource Sharing (CORS) enabled, meaning that it sends a header resembling Access-Control-Allow-Origin: *. This is due to the browser's security model, but it doesn't apply if we're loading data off the same domain, so we're able to do that without any extra work.
  • Import it as a module: Some datasets are available as modules via npm. A good example of this is earth-topojson, which we'll use when we start making maps later on. This is super convenient, as it means you just have to import the module before being able to assign it to variables. Unfortunately, the static analysis requirements of ES2015+ means that you need to have a finite dataset that can be imported at, and only at build time.
  • Connect to a websocket: Websockets are a new technology that enable the browser to subscribe to a stream and get new data pushed in real time. It's super useful for live data, but it's very memory intensive and you generally have to implement the server yourself. 
  • Insert a script tag that loads in data via JSONP and attaches to a global: JSONP is essentially a variant of JSON that is wrapped in a function callback specified by the URL. This is what people used before CORS became popular. You don't see it much any more.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset