Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RequireJS: Paths not working from require.config() [duplicate]

Even though I include my require-min.js is included, it's not picking up my paths from require.config. I've used the data-main method to load the config file.

<!--when require.js loads it will inject another script tag
    (with async attribute) for scripts/main.js-->
<script data-main="scripts/main" src="scripts/require.js"></script>

You will typically use a data-main script to set configuration options and then load the first application module. [...]

However, the aliases I am using for jQuery don't work. In my config.js file...

...
 paths: {
        jQuery: 'ThirdParty/jquery-1.8.3.min'
...

My index.html is as follows...

...
<script type='text/javascript' src='js/require.js' data-main='js/config.js'></script>
...
require(['jQuery'], function ($) {
...

This throws up the following errors sometimes on console:

GET http://<IPADDRESS>/js/jQuery.js 404 (Not Found) require.js:1895
Uncaught Error: Script error for: jQuery

I say sometimes since, say, 2 times out of 10 it loads properly. How do I solve this?

Disclaimer: A closely related question is "understanding requirejs paths". However, the answer is not complete and does not come up as top hit for this specific question. Further, it's a reasonable copy-paste from the official docs. Mods please vote down as applicable. Oh, and edit this away as applicable also ;)

like image 523
Sharadh Avatar asked Jul 30 '26 12:07

Sharadh


1 Answers

From the official docs quoted above and reading on:

Note: the script tag require.js generates for your data-main module includes the async attribute. This means that you cannot assume that the load and execution of your data-main script will finish prior to other scripts referenced later in the same page.

Solution:

Include the config file synchronously by using plain old <script> tags:

<script type='text/javascript' src='js/require.js'>
<script src='js/config.js'></script>

This solves the issue.


Additional Info

Docs

Also, you can define the config object as the global variable require before require.js is loaded, and have the values applied automatically. This example specifies some dependencies to load as soon as require.js defines require():

<script>
    var require = {
        deps: ["some/module1", "my/module2", "a.js", "b.js"],
        callback: function(module1, module2) {
            //This function will be called when all the dependencies
            //listed above in deps are loaded. Note that this
            //function could be called before the page is loaded.
            //This callback is optional.
        }
    };
</script>
<script src="scripts/require.js"></script>
like image 122
Sharadh Avatar answered Aug 01 '26 01:08

Sharadh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!