Kendall
Kendall

Reputation: 5235

Using global variables in requirejs

I'm trying to learn RequireJS and I'm a bit confused about loading global variables. I have an external script that checks to see if window.Foo has been instantiated. Which mean I need to instantiate it before I require(//url/to/external-script) the said external script

My problem is that I'm not sure how I instantiate it in requireJS

do I define() in a separate file then load that file before I load the external script?

do I create it in the requirejs.config

Upvotes: 2

Views: 2838

Answers (1)

Louis
Louis

Reputation: 151380

Global variables are not instantiated in requirejs.config. There are basically two ways to do it.

You can use a script element and put the instantiation inline or in an external script, so long as this script element appears before the one that kicks off your module loading. So:

<script>
    window.Foo = ... whatever;
</script>

The other way is to use a RequireJS module to perform the work, lets say it is called foo-config:

define(function () {
    window.Foo = ... whatever;
});

And then your module that needs to have window.Foo defined must have the above module among its dependencies. This can be problematic if you are using a 3rd party module which itself uses define to define itself as an AMD module because there is no mechanism by which you can just add dependencies to such module. You can use a nested require:

require(['foo-config'], function () {
    require(['third-party']);
});

but this is ugly, and error prone. If you have multiple pages on which you use third-party, you need to always remember to use a nested require to load it.

On the other hand, if that 3rd party module is not AMD-ready and consequently you use a shim configuration to load it, then you can add your module to the list of dependencies there.

shim: {
     'third-party': ['foo-config'];
}

Upvotes: 3

Related Questions