javascriptjqueryrequirejs

Mark script as already defined in require js


I had to move some scripts to synchronous load through bundle, and I want to set those scripts as already defined, so require.js would not ask server for them in next calls.

Let me explain:

  1. I had some scripts that were required everywhere, e.g. i18n, and jQuery. So I have hundreds if calls all around the project such as

require(['jquery', 'i18n', 'commonjs', ...

  1. I bundled 'jquery', 'i18n', 'commonjs' into one script core.js which now is inserted in layout <script src="/core.js"></script>

All functions from jQuery, i18n now can be accesses globally, without need of requiring them. I want to specifically say to reuire.js that those scripts are already loaded, something which bundles should do.

I've read article about using bundles and tried to put bundle in my config file

bundles: {
    'core': ['jquery', 'i18n', 'commonjs']
}

but it doesn't work, there lots of mistakes fallen and as I understood the only way to use bundle is to use r.js which optimizes js and folders.

Actually, all I want is to set some scripts as already loaded for require.js. Is there a dirty way to do it?


Solution

  • There's no configuration option to mark a script as already defined. What you can do is to call define yourself with a module name and an appropriate return value. For instance, if you load jQuery with a script element before you start loading any module through RequireJS, you can do:

    define("jquery", [], function () {
      return $;
    });
    

    The code above makes it so that whenever any module requires the module jquery, they get the value of $. I normally place such modules like the one just before my call to require.config. It's just a convenient place for them.