requireJS在同一個HTML/JSP頁面,載入不同版本的jquery

來源:互聯網
上載者:User

標籤:requirejs載入多版本模組   多版本模組共存   

requireJS支援JS模組化,也能夠實現在同一個HTML/JSP頁面載入不同版本的模組。這個特性太棒了,下面我們看下如何載入多個版本的jquery。假設在HTML頁面中,data-main屬性入口檔案是main.js,檔案存放的目錄結構如下:

test.html

require.js

main.js

scripts/

    demo1.js

    demo2.js

    libs/

         jquery-1.10.2.js

         jquery-2.1.1.js

 

我們在main.js編寫如下代碼:

//建立1個contextvar reqOne = requirejs.config({baseUrl: 'scripts/libs/',context:"context1",paths:{jquery: 'jquery-1.10.2'}});reqOne(['jquery'],function($) {console.log("v1=" + $().jquery);});//建立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);});

通過這種多context的方式,能夠實現多版本的模組共存。但是隨之而來也導致了2個問題:

1、如果不同context載入的模組相同,版本相同(同一個js檔案),會怎麼樣呢?這個js檔案會下載多次嗎?

結論:通過httpwatch觀察,如果不同的context載入同1個js檔案,那麼這個js檔案會下載多次。顯然這很浪費。

2、如果2個context都是需要jquery-1.10.1版本,那麼怎麼保證只js只下載一次呢?

結論:我們可以定義一個類似父類的context,存放公用的模組,各個context都可以訪問該rootContext。

//定義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);      // 訪問rootContext中的JS模組   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);      // 訪問rootContext中的JS模組   rootContext(['demo1'],function(m){    console.log("require1=" + m.name);   });               });
通過httpwatch觀察,可以看到demo1.js只會下載一次,這很好的解決了同個檔案多次下載的問題。


requireJS在同一個HTML/JSP頁面,載入不同版本的jquery

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.