0

There are a lot of questions and answers about conflicting variables names on Stackoverflow, but they all seem to be about scoping in your own code.

<script src="https://external_one/some_script.js"></script>
<script src="https://external_two/another_script.js"></script>

I'm loading two external, 3rd party JS scripts and need to run them on the same webpage. Separately they work fine, but when I try to import both at the same time, I run into a problem: both scripts have been written in such a way that they use a global _ variable. This means only the script that was imported last will work, as it overwrites the existing _ variable from the first script.

Using a global variable like this is bad practice and using a generic variable name like _ makes it even worse, but as these scripts are rather complex I can't just write my own version and I'm stuck using the scripts from these two providers. They don't seem to provide something like the 'no conflict' option libraries like JQuery provide (to prevent breaking other script that use the $ variable).

So what I'm was trying to figure out, is if it's somehow possible to encapsulate those scripts on import and prevent them from using the same variable. The only option I could think of was to use ajax to load the script, maybe make some changes and then run it using eval but this sounds like a huge problem waiting to happen.

Any suggestions on how to solve this problem?

Cerbrus
  • 70,800
  • 18
  • 132
  • 147
Jasper
  • 593
  • 2
  • 23
  • A [web worker](https://stackoverflow.com/questions/24028008/javascript-sandboxing-hide-global-variables-from-a-given-scope) might be what you need. If you need to load the scripts externally, there's [a workaround](https://stackoverflow.com/questions/23953543/cross-domain-web-workers) for that. – Cerbrus Nov 14 '22 at 10:24
  • 1
    I don't really like odd workarounds but it does seem promising. Might be faster to implement than to wait for the external devs to take action. I'll look into these workers, thanks for the suggestion. – Jasper Nov 14 '22 at 22:04

0 Answers0