How to enable lodash / underscore on a website with conflicting libraries?

I have a website that includes several third-party js modules via a tag script. I need to add lodashor underscorefor my code, but if I just add it from the CDN as follows:

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

then poorly written libraries die from a terrible death, because they expect it to _be something else. I know that lodash/ underscorehas something called "no conflict" that requires jscode to execute :

var lodash = _.noConflict();

But this code needs to be executed somewhere, and it is very difficult for me to ensure its execution before all poorly written libraries. This is an easy way to enable lodashnoconflict already, so I don’t have to look for a safe place to enable noconflict manually how lodash.min.noconflict.js?

+8
source share
2 answers

As long as there are no corresponding asynchronous 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>
<script>
_u = _.noConflict(); // lets call ourselves _u
</script>

It doesn't matter if other scripts install / use _ before or after. (lodash remembers the last value of _ and restores it when calling _.noConflict ().)

, , . AMD, script, lodash, .

+9

CDN - 4.17.15 :)

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"> </script>
<script>
_u = _.noConflict();
</script>
+2

Source: https://habr.com/ru/post/1568272/


All Articles