I need to dynamically load a JS file which exports a variable to the window
object (e.g. React or jQuery) and get the exported value without changing the page window
object. How can I do it using JavaScript?
It should work like this:
(function () {
var React = someMagic();
assertNotEmpty(React);
assertEmpty(window.React);
})();
What is my end goal: make a script for embedding to other websites. The script performs some actions with the page where it is installed, requires some dependencies, but the dependencies must not interfere with the page dependencies.
Using AMD or Require.js is not suitable because it changes the page scripts behaviour (they stop exporting variables to window
) which can break the page.
Using a solution like this:
<script src="jquery.js"></script>
<script>
(function () {
var jQuery = jQuery.noConflict();
})();
</script>
Is also not suitable because it requires changing HTML while I can use only JavaScript.
Joining the script with the dependencies and wrapping it all with (function(){ ... })()
is not suitable too.