Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
Module, AMD, RequireJS
Search
othree
May 19, 2012
Technology
11
4k
Module, AMD, RequireJS
othree
May 19, 2012
Tweet
Share
More Decks by othree
See All by othree
How GitHub Supports Vim License Detection, The Five Years Journey
othree
1
1.9k
WAT JavaScript Date
othree
3
1.9k
Modern HTML Email Development
othree
3
2.6k
MRT & GIT
othree
1
2.1k
YAJS.vim and Vim Syntax Highlight
othree
1
2.7k
Web Trends to 2015
othree
4
310
Transducer
othree
9
2.9k
HITCON 11 Photographer
othree
4
480
fetch is the new XHR
othree
6
3.5k
Other Decks in Technology
See All in Technology
LangChainとLangGiraphによるRAG・AIエージェント実践入門「10章 要件定義書生成Alエージェントの開発」輪読会スライド
takaakiinada
0
130
AWSのマルチアカウント管理 ベストプラクティス最新版 2025 / Multi-Account management on AWS best practice 2025
ohmura
4
210
20250413_湘南kaggler会_音声認識で使うのってメルス・・・なんだっけ?
sugupoko
1
400
Android는 어떻게 화면을 그릴까?
davidkwon7
0
100
Amebaにおける Platform Engineeringの実践
kumorn5s
6
900
2025年春に見直したい、リソース最適化の基本
sogaoh
PRO
0
460
Automatically generating types by running tests
sinsoku
1
470
Classmethod AI Talks(CATs) #21 司会進行スライド(2025.04.17) / classmethod-ai-talks-aka-cats_moderator-slides_vol21_2025-04-17
shinyaa31
0
460
ブラウザのレガシー・独自機能を愛でる-Firefoxの脆弱性4選- / Browser Crash Club #1
masatokinugawa
1
400
7,000名規模の 人材サービス企業における プロダクト戦略・戦術と課題 / Product strategy, tactics and challenges for a 7,000-employee staffing company
techtekt
0
260
食べログが挑む!飲食店ネット予約システムで自動テスト無双して手動テストゼロを実現する戦略
hagevvashi
2
220
Startups On Rails 2025 @ Tropical on Rails
irinanazarova
0
250
Featured
See All Featured
Bash Introduction
62gerente
611
210k
Done Done
chrislema
183
16k
Optimising Largest Contentful Paint
csswizardry
36
3.2k
Being A Developer After 40
akosma
91
590k
Building a Scalable Design System with Sketch
lauravandoore
462
33k
Reflections from 52 weeks, 52 projects
jeffersonlam
349
20k
個人開発の失敗を避けるイケてる考え方 / tips for indie hackers
panda_program
104
19k
How GitHub (no longer) Works
holman
314
140k
It's Worth the Effort
3n
184
28k
Dealing with People You Can't Stand - Big Design 2015
cassininazir
367
26k
How to Ace a Technical Interview
jacobian
276
23k
Thoughts on Productivity
jonyablonski
69
4.6k
Transcript
Module, AMD, RequireJS othree @ JSDC 2012
Object
Object Oriented Programming
Why OOP • Maintainable & Scalable • Gathering related variables
& methods
Object from OOP • Inheritance • Polymorphism • Encapsulation
Encapsulation • A language mechanism for restricting access to some
of the object's components. http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming)
Why Encapsulation • Protect variable from unwanted change
JavaScript is Prototype-based
Private Data in JavaScript
Naming Convention function Human(sgender) { //Private this._age = 1; this._gender
= sgender || 'Male'; //Public this.growUp = function () { this._age++; }; }
Human _age _gender growUp Accessible Anywhere
Privileged Method function Human(sgender) { //Private var age = 1,
gender = sgender || 'Male'; //Privileged Method this.growUp = function () { age++; }; } http://javascript.crockford.com/private.html
Human age gender growUp Accessible Anywhere
Module Pattern
Module Pattern function Human(sgender) { //Private var age = 1,
gender = sgender || 'Male'; //Public return { growUp: function () { age++; } }; } http://yuiblog.com/blog/2007/06/12/module-pattern/
Accessible Anywhere exports Human age gender growUp
Advantage • Easy • Keep private data safe
Disadvantage • Hard to inherit
Large Application • Lots of modules • Complex dependency
Lots of Modules • One file per module • Lots
of files: • Performance Issue • Async loading?
Complex Dependency • Load modules by order • Hard to
know the order by head and hand
Solution? • Not hard to solve • But there is
no standard API
CommonJS
CommonJS • by Kevin Dangoor • Volunteers and mailing list
• Unify server side JavaScript API • Build JavaScript ecosystem • Not an official organization
CommonJS APIs • Binary • Filesystem • IO • ...
• Modules
None
CommonJS Module • Modules/1.0 • NodeJS • Modules/AsynchronousDefinition • AMD
AMD
Asynchronous Module Definition define(id?, dependencies?, factory);
Example define( 'account', ['service', 'pubsub'], function (service, pubsub) { //do
something //export public APIs return { signin: function () { /* ... */ }, signout: function () { /* ... */ }, getName: function () { /* ... */ }, setName: function () { /* ... */ } }; } );
Another Way (function () { //10000 lines of code exports
= { signin: function () { /* ... */ }, signout: function () { /* ... */ } }; define('account', function () { return exports; }); }());
In jQuery if ( typeof define === "function" && define.amd
&& define.amd.jQuery ) { define( "jquery", [], function () { return jQuery; } ); }
RequireJS
RequireJS • AMD Implementation by James Burke • Async resource
loader • 1.0.8 now, 2.0 under development
Usage <script data-main="main" src="require.js"></script>
main.js require(["app"], function(app) { app.init(); });
app.js define(["lib/account", "lib/session"], function (account, session) { //do something return
{ init: function () { //init the application } }; } );
main.js account.js app.js session.js crypt.js xhr.js storage.js
Features • AMD • Path alias • Circular dependency •
Plugins
Plugins • order • text • wrap, use • cs
(CoffeeScript)
Advantages • No pollution to global scope • Everything is
organized in module • Compile CoffeeScript on the fly • ...etc
Minefield • Module load fail: hard to debug • Wrong
path • Use require function • Plugin error, ex: CoffeeScript syntax error
Still Problems • Lots of modules • Lots of files
• Lots of requests • Low performance
r.js
r.js • Optimization tool • Pack all modules into one
file • Minimize the JavaScript file
Usage node r.js -o build.js
build.js ({ appDir: "../", baseUrl: "scripts", dir: "../../appdirectory-build", modules: [
{ name: "main" } ] })
main.js account.js app.js session.js crypt.js xhr.js storage.js
After Optimized • require.js are large: 86kb
almond.js
almond.js • Minimal AMD API implement • Same author
Advantages • Small: 9kb, 857 bytes minimized and gzipped •
Stable: no change since 0.0.3
Disadvantages • No plugin support • Not a resource downloader
• Lots of restriction • Different optimize concept
Usage node r.js -o baseUrl=. name=path/to/almond.js include=main out=main-built.js wrap=true
Tip • You can use r.js to optimize • And
use almond.js to replace require.js
<script src="almond.js"></script> <script src="main-optimized.js"></script>
References • http://www.yuiblog.com/blog/2007/06/12/module-pattern/ • http://wiki.commonjs.org/wiki/Modules/1.1 • http://wiki.commonjs.org/wiki/Modules/AsynchronousDefinition • https://github.com/amdjs/amdjs-api/wiki/AMD •
http://requirejs.org/ • https://github.com/jrburke/almond
None
Questions Time
Q • I want to use Underscore and Backbone, but
they don’t support RequireJS....
A • Do nothing • Use use/wrap plugin • Use
modified version https://github.com/jrburke • Use another script tag to include them first
<script src="undersocre+backbone.js"></script> <script src="almond.js"></script> <script src="main-optimized.js"></script>
<script src="yepnope.js"></script> <script> yepnope({ load: [ "undersocre+backbone.js", "almond.js", "main-optimized.js" ]
}); </script>
Questions?
Thank You