javascript
菜鸟requireJS教程---1、初识requirejs
菜鳥requireJS教程---1、初識requirejs
一、總結
一句話總結:
Using a modular script loader like RequireJS will improve the speed and quality of your code.
?
1、requirejs優點?
1、防止js加載阻塞頁面渲染
2、使用程序調用的方式加載js,防出現要寫很多要加載js的場景
?
2、JS阻塞瀏覽器渲染 實例?
|||-begin
index.html:<!DOCTYPE html> <html><head><script type="text/javascript" src="a.js"></script></head><body><span>body</span></body> </html> a.js:function fun1(){alert("it works"); }fun1();可能你更喜歡這樣寫(function(){function fun1(){alert("it works");}fun1(); })() 第二種方法使用了塊作用域來申明function防止污染全局變量,本質還是一樣的|||-end
alert執行的時候,html內容是一片空白的,即<span>body</span>并未被顯示,當點擊確定后,才出現
?
?
?
二、初識requirejs
轉自或參考:JS模塊化工具requirejs教程(一):初識requirejs | 菜鳥教程
https://www.runoob.com/w3cnote/requirejs-tutorial-1.html
隨著網站功能逐漸豐富,網頁中的js也變得越來越復雜和臃腫,原有通過script標簽來導入一個個的js文件這種方式已經不能滿足現在互聯網開發模式,我們需要團隊協作、模塊復用、單元測試等等一系列復雜的需求。
?
RequireJS是一個非常小巧的JavaScript模塊載入框架,是AMD規范最好的實現者之一。最新版本的RequireJS壓縮后只有14K,堪稱非常輕量。它還同時可以和其他的框架協同工作,使用RequireJS必將使您的前端代碼質量得以提升。
requirejs能帶來什么好處
官方對requirejs的描述:
RequireJS is a JavaScript file and module loader. It is optimized for in-browser use, but it can be used in other JavaScript environments, like Rhino and Node. Using a modular script loader like RequireJS will improve the speed and quality of your code.
大致意思:
在瀏覽器中可以作為js文件的模塊加載器,也可以用在Node和Rhino環境,balabala...。這段話描述了requirejs的基本功能"模塊化加載",什么是模塊化加載?我們要從之后的篇幅中一一解釋
先來看一段常見的場景,通過示例講解如何運用requirejs
正常編寫方式
index.html:
<!DOCTYPE html> <html><head> <script type="text/javascript" src="a.js"></script> </head> <body> <span>body</span> </body> </html>a.js:
function fun1(){alert("it works"); } fun1();可能你更喜歡這樣寫
(function(){function fun1(){ alert("it works"); } fun1(); })()第二種方法使用了塊作用域來申明function防止污染全局變量,本質還是一樣的,當運行上面兩種例子時不知道你是否注意到,alert執行的時候,html內容是一片空白的,即<span>body</span>并未被顯示,當點擊確定后,才出現,這就是JS阻塞瀏覽器渲染導致的結果。
requirejs寫法
當然首先要到requirejs的網站去下載js ->?requirejs.org
index.html:
a.js:
define(function(){function fun1(){ alert("it works"); } fun1(); })瀏覽器提示了"it works",說明運行正確,但是有一點不一樣,這次瀏覽器并不是一片空白,body已經出現在頁面中,目前為止可以知道requirejs具有如下優點:
?
文章來源:https://github.com/liuxey/blog/issues/1
?
?
?
?
?
轉載于:https://www.cnblogs.com/Renyi-Fan/p/11590708.html
總結
以上是生活随笔為你收集整理的菜鸟requireJS教程---1、初识requirejs的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: JavaScript_AMD规范
- 下一篇: 菜鸟requireJS教程---2、基本