Eye of Hell Eye of Hell - 4 months ago 42
HTML Question

How to correctly include lodash/underscore on website with conflicting libs?

I have a website that includes a number of third-party js modules via

tag. I need to add
for my code, but if I simply add it from CDN like this:

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.min.js"></script>

then badly written libs die terrible death because they expect
to be something else. I know that
have something called "no conflict" mode, that requires
code to be executed:

var lodash = _.noConflict();

But this code needs to be executed somewhere, and it's really hard for me to ensure that it's executed before all badly written libs. Is it any simple way to include
already in noconflict mode, so i don't need to search for a safe place to enable noconflict mode manually? like


As long as there are no relevant async scripts before the manual method, it should always work:

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.min.js"></script>
_u = _.noConflict(); // lets call ourselves _u

It makes no difference if other scripts set/use _ before or after this. (lodash remembers the last setting of _ and restores it on the _.noConflict() call.)

But if scripts before this are async there is always a possibility that they are allowed to execute between these two scripts. You would have to either use AMD or combine the manual setting into the same script as lodash to avoid races with async scripts.