How to load multiple D3 versions at once

Today I am writing a short tutorial on how you can load multiple D3.js versions at once.

Why you might want to load multiple D3 versions?

Most of the time you will be using the same version of D3 for all visualisations on the page.

However there may be cases where multiple visualisations must be loaded on the page, and only work with specific versions of D3.

How to load multiple D3 versions

When D3.js loads it creates a d3 object in the main window. The fully qualified name for this is window.d3. To load multiple versions you need to save the contents of this variable to another name, and then clear it.

For all of these examples I am linking directly to the d3 code available at d3js.org.

<script src="https://d3js.org/d3.v5.js"></script>
<script>
	var d3v5 = window.d3;
	window.d3 = null;
</script>
<script src="https://d3js.org/d3.v4.js"></script>

First you need to import the first version of d3 you want to load. In this case I am importing d3 version 5. Once it has loaded it is accessed using window.d3 and saved in a variable d3v5.

Since this is an object, the object reference is copied and the actual data does not change.

Once it is loaded it is important to completely nullify the reference to it within window.d3. This is done by setting the variable equal to null.

This is important because d3.js will reuse the d3 object if it is found, causing it to become a hybrid of versions potentially causing numerous unknown issues.

Once window.d3 is cleared you are able to load the next version of d3. This again will be loaded into window.d3 and can be used as needed. In the example above d3 version 4 is loaded.

Using the different D3 versions

Once you have loaded all the D3 versions that you are expecting to use, you can begin to use them.

<div>d3 variable version: <span id="d3VarVer"></span></div>
<div>d3v5 variable version: <span id="d3v5VarVer"></span></div>

<script>
    document.getElementById("d3VarVer").innerText = d3.version;
    document.getElementById("d3v5VarVer").innerText = d3v5.version;
</script>

Here I am writing d3.version and d3v5.version into two span’s in the HTML. While the example is trivial you can use the full range of functions d3 provides with either d3 version on the page.

Summary on using multiple D3 versions on a page

By saving the value of window.d3 to another variable you can load multiple versions on the same page. When doing this it is important to clear the value of window.d3 before loading the next version to avoid issues.

Once all the versions of D3.js has been loaded you will be able to use them as needed.

The full code for this is available on my website which includes a live example.

If you have any questions feel free to comment on the following blog post.

One Comment

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.