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.
The JavaScript ecosystem has completely changed during this time, in terms of libraries, best practices and even language features. Nevertheless, D3 is still here. And it's more popular than ever.
We have compiled a list of solutions that reviewers voted as the best overall alternatives and competitors to D3js, including Syncfusion Essential Studio Enterprise Edition, Chart. Js, Angular, and DevExpress.
D3 is a very large set of modules with high customizability, so it can seem overwhelming to learn. The difficulty likely depends on an individual's experience with JavaScript, HTML and basic web development. It can be a steep learning curve for new programmers because there may be a lot of new concepts.
D3.js is a JavaScript library for manipulating documents based on data. D3 helps you bring data to life using HTML, SVG, and CSS.
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:
d3versionX = d3;
d3 = d3versionX
where X is your default version for the visualization when the page loadsSee 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>
I had a similar problem like yours, some visualization needed d3 v3 while others needed v4. This is how I achieved it.
write the following code at the top.
function graphicviz(id) {
require.config({
paths: {
d3: "https://d3js.org/d3.v4.min"
}
});
require(["d3"], function(d3) {
//... D3 Code Here...
});
}
//Call The Function
graphicviz(id);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With