Background Info
My team has a React JS application that's gotten very large over time - as such, we're looking at breaking it into smaller pieces. Currently, we're considering loading those pieces using <script> tags. These pieces may be created / managed by other teams.
Our main (shell, container) application uses variety of 3rd party libraries. Many of these libraries create objects on window (such as window.errorlibrary, window.logginglibrary, etc). Additionally, we capture unhandled exceptions using window.onerror.
Other teams will likely want to use many of the same 3rd party libraries we are using. Additionally, they may also want to perform their own error handling on unhandled exceptions in their code.
The Problem
When you load JS using a <script> tag, that loaded JS now has the same window object as the main (shell, container) application. These means that if the main application is using window.errorlibrary, and the loaded JS has a window.errorlibrary, the loaded JS will overwrite the original window.errorlibrary. The same thing happens to error handling defined using window.onerror.
I've also tested webpack 5 module federation, and the same issue occurs (JS sharing the window object).
Additional Info
I'm aware that using <iframe>s instead of <script>s would fix this issue (since the loaded JS would then be executing in it's own window). I'm also aware that we could coordinate to name any objects we attach to window uniquely, but that won't necessarily work for 3rd party libraries or for error handling with window.onerror.
We may ultimately need to just use <iframe>s, but I'd like to see if there's another option.
I think the only way to achieve this is by namespacing your modules. If this description works for you:
In many programming languages, namespacing is a technique employed to avoid collisions with other objects or variables in the global namespace. They're also extremely useful for helping organize blocks of functionality in your application into easily manageable groups that can be uniquely identified.
and it's easily achievable then I would go for this. P.s. Here's a link to a really detailed article about the namespacing patterns: https://addyosmani.com/blog/essential-js-namespacing/