简体   繁体   中英

How do I use two versions of the same javascript library without bleeding functions in the same page?

I have a use case where I need to use multiple versions of the Nvd3 library for different charts on the same page in an angular application (Each chart is loaded through a separate template). How do I avoid such a collision?

So, let's say the graph on partial_1.html requires a v1.8, graph on partial_2.html requires v1.1 and so on. Any help would be highly appreciated.

jQuery tries to fix this using the noConflict method, but I can't seem to find a solution that works for arbitrary js libraries (not just jQuery).

If you cannot update the older charts to use the most recent version, then you have only one option, and that is to rename the global variable "d3" for each version that you are using. Then, you should do a find and replace on each template to change the referenced variables. That way each points to a specific version. You could accomplish this with code that looks something like this:

(function (w, d) {
    "use strict";
    var h = d.getElementsByTagName("head")[0],
        s = d.createElement("script");
    w.d3 = null;
    s.src = "https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.3/d3.min.js";
    s.onload = function () {
        w.d3_3_5_3 = w.d3;
        w.d3 = undefined;
        s = d.createElement("script");
        s.src = "https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.4/d3.min.js";
        s.onload = function () {
            w.d3_3_5_4 = w.d3;
            w.d3 = undefined;
            s = d.createElement("script");
            s.src = "https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js";
            s.onload = function () {
                w.d3_3_5_5 = w.d3;
                w.d3 = undefined;
            };
            h.appendChild(s);
        };
        h.appendChild(s);
    };
    h.appendChild(s);
}(window, document));

The example above loads three versions, and by using the onload event, it captures each new instance of d3 and puts it into its own variable. In this case, d3_3_5_3, d3_3_5_4, and d3_3_5_5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM