Require Js - search for hybrid requirejs implementation in "Not fully client application"

It's been a few days when I learn requirejs (JavaScript module loader for loading modules and dependencies asynchronously).

I figured out that you need all your JavaScript libraries or plugins (like JQuery, etc.) to be loaded in require.config to be used as a dependency in any custom module you create, or any other plugin that you are using directly depends on jquery or any other lib.

I'm not sure and skeptical if it can be used in an already built application where I want some of my plugins or libraries that depend on JQuery to be defined / used with requirejs and another application javascript continue using jquery in the form strings.

That is: I am including jquery using a script tag, not via require.config, but I want to use and include another plugin / JavaScript using js that depend on JQuery.

In short, I need a hybrid requirejs implementation in my already built server application, which is not a fully client application.

A code snippet or instruction is very helpful.

+3


source to share


1 answer


Yes, it is possible if you are careful in your actions.

All elements script

that load JavaScript code whose code is loaded with RequireJS must look before any code that triggers the module to load using RequireJS. This is the only way to make sure what you need is available when RequireJS starts loading modules.

Then you have the option to have modules loaded with RequireJS, just assume that the loaded with script

made itself available in the global scope and use it without adding it to your dependencies. For example, if a module needs jQuery and has already been loaded by an element script

, then the module would assume it was $

already defined:

define(function () {
    $("p").append(...);
});

      

For third-party code that has already specified dependencies on the code you load with elements script

, or if you prefer to make dependencies in code that you write explicitly, you need to use "glue modules". ( This is the option I prefer for my own code. ) The same module above formally requires jQuery:



define(["jquery"], function ($) {
    $("p").append(...);
});

      

and you will need to have a "glue module" for jquery

. I usually place such modules just before my call, require.config

instead of putting them in separate files. It will be something like:

define('jquery', function () {
    return $;
});

      

Note that the first parameter to call define

here is a string (not an array) that tells RequireJS that the module has a name jquery

. Usually you shouldn't give names like for this, but for glue modules. The glue module makes the assumption that it is $

defined and is jQuery. Any module that needs jQuery depends on that module. If at a later stage jQuery is loaded as a RequireJS module, then the glue module can be removed and none of the jQuery dependent modules need to be changed.

+2


source







All Articles