score:14

Accepted answer

You can download the version 3 of the script locally and change the last line from

this.d3 = d3;

to

this.d3v3 = d3;

So you can use d3 version 4 calling d3, and the version 3 of the library calling d3v3

score:0

I Use RequireJS to resolve this issue

  • treelist d3 Version : 3

         require( ["js/common/d3.v3.min"], function(d3) {
            // tree list code here
           });
    
  • treemap d3 Version : 4

    require( ["js/common/d3.v4.min"], function(d3) {       
    // treemap code here
    

    }

Note : You need to import require.js file : download it from here

http://requirejs.org/docs/1.0/docs/download.html

put the import statement at the end of body tag i.e.

< body>

// code ....

< /body >

score:8

(I don't know why you are trying to do this, or if this is really necessary. Have in mind that I'm just answering your question, that is, how to use D3 v3 and v4 in the same page, without analysing your objectives or if this is an XY problem).

As you must know by now, you cannot just reference both versions in the HTML:

<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://d3js.org/d3.v3.min.js"></script>

Because, obviously, that will cause a conflict when you use d3 to call the methods.

Thus, the solution is downloading one of the two versions and changing the source code.

In this solution, I'll change the source code of the v4.x version (minified) and use the regular reference to the v3. You can do the other way around (as Daniela did in her answer), but the steps are not the same.

In D3 v4.x (minified), you see this at the beginning:

// https://d3js.org Version 4.9.1. Copyright 2017 Mike Bostock.
(function(t, n) {
    "object" == typeof exports && "undefined" != typeof module ?
        n(exports) : "function" == typeof define && define.amd ?
        define(["exports"], n) : n(t.d3 = t.d3 || {})
}) etc...

What I'm gonna do is changing that t.d3 to t.d3v4 (or any other name you want).

After that, you can use d3 to call your D3 v3 functions and d3v4 (not d3) to call your D3 v4 functions.

Like in this example:

var scalev3 = d3.scale.linear()
    //note:    ^----- use `d3` for D3 v3 functions
    .range([0, 5000])

var scalev4 = d3v4.scaleLinear()
    //note:     ^----- use `d3v4` for D3 v4 functions
    .range([0, 200]);

console.log(scalev3(0.4))//logs 2000, as expected.
console.log(scalev4(0.4))//logs 80, as expected.

Here is the plunker with that code: https://plnkr.co/edit/h174Gcc3YSCJGpNljCOh?p=preview


Related Query

More Query from same tag