Search code examples
javascriptrequirejsunderscore.jsamd

Load timeout for modules with requirejs


I'm using requirejs to load some libraries and dependencies.

When I just load jQuery, it's working perfectly:

main.js

require.config({
  shim: {
    jquery: {
      exports: '$'
    }
  },
  paths: {
    jquery: 'vendor/jquery'
  }
});

require([
  'vendor/jquery',
  'app/init'
]);

app/init.js

define(
  ['jquery'],
  function ($) {
    $(document).ready(function () {
      console.log('domready');
    })
  }
)

But when I try to add underscore, in the network panel the file is correctly loaded but in the console I get a

Uncaught Error: Load timeout for modules: underscore

What's happening? I also tried the waitSeconds: 200 options inside the require.config without any success.

Below the final (broken) code as a reference:

main.js

require.config({
  shim: {
    jquery: {
      exports: '$'
    },
    underscore: {
      exports: '_'
    }
  },
  paths: {
    jquery: 'vendor/jquery',
    underscore: 'vendor/underscore',
  }
})

require([
  'vendor/jquery',
  'vendor/underscore',
  'app/init'
])

app/init.js

define(
  ['jquery', 'underscore'],
  function ($, _) {
    $(document).ready(function () {
      console.log('domready');
    })
  }
)

Solution

  • In define and require calls you sometimes refer to your modules as "vendor/<name of module>" and sometimes as "<name of module>". This is wrong. Based on the config you show you should refer to your modules as "<name of module>" in all require and define calls. So always refer to jQuery and Underscore as "jquery" and "underscore", not "vendor/.... When you refer to them with the full path you bypass the shim configuration.

    Actually, you can change your require call to:

    require(['app/init']);
    

    You don't need to refer to jQuery and Underscore there. They will be loaded when app/init.js is loaded due to the define there requiring them.

    (Also, relatively recent versions of jQuery don't need a shim because jQuery detects that it is loaded by an AMD-compatible loader and calls define itself. This is not the source of your problem but it is good to know.)