multiple versions of a script on the same page (d3.js)

d3.js, javascript, jquery

Solution

If you take a look at the main d3 source file: https://github.com/mbostock/d3/blob/master/d3.js

you see it begins:

d3 = function() {
  var d3 = {
    version: "3.1.5"
  };
  //.....

So d3 is just an object. I'm not sure if this is the best method, but I think the following would work:

- include one version of d3

- put the line: `d3versionX = d3;`

- include the next version

- same as 2 with different version number.

- put `d3 = d3versionX` where X is your default version for the visualization when the page loads

- put an event handler on the thumbnails that trigger the switching of version, and set the d3 variable to the appropriate version number as the first thing that happens.

update with sample code

See this jsbin for a working example. The relevant code:

  <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.10.0/d3.min.js"></script>
  <script>
    d3version4 = d3
    window.d3 = null
  </script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.min.js"></script>
  <script>
    d3version3 = d3
    window.d3 = null
    // test it worked
    console.log('v3', d3version3.version)
    console.log('v4', d3version4.version)
  </script>

Problem

I need to have multiple versions of a javascript library on the same page. How can I accomplish this, short of manually refactoring one version to avoid naming conflicts? There are many examples of how to do this with Jquery (example). This seems to rely on jQuery goodness, however. How can I do this for an arbitrary script? More detail: I'm using d3.js, and I'm plugging in visualizations others have made using d3. The issue is, one of the vizzes requires one version of d3, the other requires a newer version. Both of these vizzes are supposed to be available on the same page - the user swaps which viz is displayed by clicking a thumbnail, and then js is used to hide one viz and build the other. So, it seems like swapping the script rather than loading both in a no-conflict style could also be an option.

Original source

Related problems