Requirejs Support JS modularity, but also can be implemented on the same html/jsp page load different versions of the module. This feature is awesome, let's look at how to load multiple versions of jquery. Suppose that in an HTML page, the Data-main property entry file is Main.js, and the directory structure of the file is as follows:
Test.html
Require.js
Main.js
scripts/
Demo1.js
Demo2.js
libs/
Jquery-1.10.2.js
Jquery-2.1.1.js
We write the following code in Main.js:
Create 1 Contextvar reqone = Requirejs.config ({baseUrl: ' scripts/libs/', Context: ' Context1 ', Paths:{jquery: ' jquery-1.10.2 '}}); Reqone ([' jquery '],function ($) {Console.log ("v1=" + $ (). jquery);}); /create 1 Contextvar reqtwo = Requirejs.config ({baseUrl: ' scripts/libs/', Context: ' Context2 ', Paths:{jquery: ' jquery-2.1.1 '}}); Reqtwo ([' Require ', ' jquery '],function (require,$) {console.log ("v1=" + $ (). jquery);});
This multi-context approach enables multiple versions of the module to coexist. But it also led to 2 problems:
1, if different context load module is the same, the same version (the same JS file), what happens? will this JS file be downloaded multiple times?
Conclusion: Through HttpWatch observation, if different context load the same 1 JS file, then this JS file will be downloaded multiple times . Obviously it's a waste.
2, if 2 of the context is required jquery-1.10.1 version, then how to ensure that only JS download only once?
Conclusion: We can define a context similar to the parent class, and store the public module, which can be accessed by each context.
Definition Rootcontextvar Rootcontext = require.config ({baseUrl: ' scripts/'}); var reqone = Requirejs.config ({baseUrl: ' scripts/libs/', Context: "Context1", paths:{ jquery: ' jquery-1.10.2 '}}); Reqone ([' jquery '], function ($) { Console.log ("v1=" + $ (). jquery); Access the JS module in Rootcontext rootcontext ([' Demo1 '],function (m) { console.log ("require1=" + M.name);}) ; var reqtwo = Requirejs.config ({baseUrl: ' scripts/libs/', Context: "Context2", paths:{ jquery: ' jquery-2.1.1 ' }}); Reqtwo ([' Require ', ' jquery '], function (require,$) { console.log ("v1=" + $ (). jquery); Access the JS module in Rootcontext rootcontext ([' Demo1 '],function (m) { console.log ("require1=" + M.name);}) ;
by HttpWatch observation, you can see that demo1.js will only be downloaded once, which solves the problem of multiple downloads of the same file.
Requirejs on the same html/jsp page, loading different versions of jquery