Your SlideShare is downloading. ×
An Introduction to Inject
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×

Introducing the official SlideShare app

Stunning, full-screen experience for iPhone and Android

Text the download link to your phone

Standard text messaging rates apply

An Introduction to Inject

3,162
views

Published on

Given at the Front End Developers United Meetup in Mountain View, CA

Given at the Front End Developers United Meetup in Mountain View, CA


0 Comments
5 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
3,162
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
16
Comments
0
Likes
5
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide
  • Thanks everyoneFeel free to pepper me with questions as we goWe’ll tour how we got from script tags to module loaders, talk about Inject, and dive in to the APIBy the end, you should have a good sense that loaders rock, Inject’s pretty cool, and you can’t wait to go home and fork it 
  • This is meWell, me with a deadmau5 headI’m a web developer here [NEXT]
  • At a company that lets me wear a crazy deadmau5 head on halloween.I work with about 80 other web developersAnd we build [NEXT]
  • The linkedin homepage
  • The profile
  • News channels
  • Mobile, and more
  • In the beginning
  • We used script tags in our pageBefore the closing body tag
  • Blocking (less painful in the footer)Very manualMay not have needed everything you were loading
  • We got a bit smarterSteveSouders with “Blocking” and how to load resources asynchronouslyScript tags added via JS would not interfere with the loading of the page
  • This created libraries (like any good technique does on the internet)
  • And libraries made things even betterThis example is using lab.js to load a jquery instance, some shared code, some app code, and then run a callback when everything is loadedSome libraries went so far as you enable the loading of CSS as well
  • And along came the big frameworksYUI 2 had a loader utility, and YUI 3 made asset loading a piece of the framework via the YUI.use() syntax
  • Dojo since early on in its project had loading files as a fundamental pieceThe dojo.require syntax defined the framework
  • Then along came this “node” “js” “thing”And everything changed.Require() became the hot new way to include code. It was easy to understandCall the function “require”, get back a usable javascript object.There was one problem. In the world of node, require() was synchronous. How do you synchronously download files on the internet?
  • Along came some libraries to bring this to the browserBower, ender, browserfyThe first class, we’ll call them packagers let you use require(), and it would magically work
  • The tradeoff for these packagers was your delivery of payload in a single shot.However, for most people who were looking to write single page apps (and potentially fulfill the magical dream of sharing code on the client and server), this is what the hoped for
  • Most packagers implement what is defined as the commonJS standard (commonjs.org)Specifically the use of a require() functionIn an attempt to think about browsers, the commonJS folks created require.ensure (the async/a proposal for the trivia fans) but it didn’t really account for how a browser might naturally want to include code
  • So again, on the internet, libraries were madeInject, Dojo, RequireJS, Curl, NeedsJS, LSJS all implement a standard known as AMDAsynchronous Module Definition
  • Like CommonJS, but more browser friendly, AMD uses a define() functionIt allows you to specify dependenciesIt then has a callback function on completion
  • Some day, many of these problems go away. Harmony Modules in ECMAScript will make this all magically work in every javascript environmentUnless you find yourself supporting IE 7, in which case you’re not using these for quite some time
  • So that’s the landscape, let’s talk about how you would get started using Inject
  • Files with _amd are for AMD loadersFiles with _cjs are for CJS loaders and packagersInject works with both syntaxes. You can even mix and match
  • Injectjs.com is a great resource. Downloads, documentation, mailing list
  • Create a modules directory where you will put all your code
  • Note CJS and AMD syntax
  • First, add a script tag with injectTowards the end of your page, tell Inject where your modules directory isThen, run the program!
  • WOW!
  • Inject’s primary API is easy to work withAlready used some of it in our setup example
  • setModuleRoot – find files
  • setExpires : adjust localStorage
  • Inject.reset big reset button
  • You can also do some really awesome stuff with the advanced API. While there are more items on injectjs.com, we’re going to talk about addRule
  • Transcript

    • 1. INJECTJakob Heuser – maintainer@InjectJS©2012 LinkedIn Corporation. All Rights Reserved.
    • 2. ©2012 LinkedIn Corporation. All Rights Reserved. 2
    • 3. ©2012 LinkedIn Corporation. All Rights Reserved. 3
    • 4. ©2012 LinkedIn Corporation. All Rights Reserved.
    • 5. ©2012 LinkedIn Corporation. All Rights Reserved.
    • 6. ©2012 LinkedIn Corporation. All Rights Reserved.
    • 7. ©2012 LinkedIn Corporation. All Rights Reserved.
    • 8. LinkedIn’s Web Development 6+ Vertical Engineering Groups 80+ Web Developers (horizontal) linkedin.com – Main Site – Tools for Recruiters – Mobile Products Performance is a shared goal in the frontend©2012 LinkedIn Corporation. All Rights Reserved. LINKEDIN UED 8
    • 9. Performance has Come a Long Way©2012 LinkedIn Corporation. All Rights Reserved.
    • 10. ©2012 LinkedIn Corporation. All Rights Reserved. LINKEDIN UED 10
    • 11. In The Beginning <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="shared.js"></script> <script type="text/javascript" src="app.js"></script></body></html>©2012 LinkedIn Corporation. All Rights Reserved. LINKEDIN UED 11
    • 12. In The Beginning Blocking (less painful in the footer) Very manual May not have needed everything you were loading©2012 LinkedIn Corporation. All Rights Reserved. LINKEDIN UED 12
    • 13. Async loadingvar load = [jquery.js, shared.js, app.js];var head = document.getElementById(head)[0];var scr;for (var i = 0, len = load.length; i < len; i++) { scr = document.createElement(script); scr.type = text/javascript; scr.src = load[i]; head.appendChild(scr);}©2012 LinkedIn Corporation. All Rights Reserved. LINKEDIN UED 13
    • 14. Async Loader Libraries©2012 LinkedIn Corporation. All Rights Reserved. LINKEDIN UED 14
    • 15. Things got better$LAB .script("jquery.js") .script("shared.js").wait() .script("app.js").wait(function() { // all code loaded });©2012 LinkedIn Corporation. All Rights Reserved. LINKEDIN UED 15
    • 16. Framework natives// in your app code...YUI({ modules: { shared: { fullpath: http://example.com/js/shared.js, requires: [get, node] } }}).use(shared, function(Y) { // In YUI, "Y" is decorated with functionality});// in shared.js...YUI.add(shared, function(Y) { // add function to the "Y" object});©2012 LinkedIn Corporation. All Rights Reserved. LINKEDIN UED 16
    • 17. Framework natives// note, this is Dojo 1.7// Dojo 1.8 uses AMD and were getting to that!dojo.require(shared.js);dojo.ready(function() { // custom code});©2012 LinkedIn Corporation. All Rights Reserved. LINKEDIN UED 17
    • 18. ©2012 LinkedIn Corporation. All Rights Reserved. LINKEDIN UED 18
    • 19. And We Brought it to the Browser©2012 LinkedIn Corporation. All Rights Reserved. LINKEDIN UED 19
    • 20. Browser Packaging Solutions Put together discrete pieces into one payload Support the asynchronous require() method – I want “X”, so… var x = require(“X”); Excellent single page application solutions©2012 LinkedIn Corporation. All Rights Reserved. LINKEDIN UED 20
    • 21. The CommonJS Standard var myVar = require(“string”) – Returns the “string” module’s items assigned to the module’s “exports” variable – Require is a global variable (always available) require.ensure(dependencies, function() {}) – The “Asynchronous/A” Draft – Download all of the dependencies (an array) – Then run the callback function (second param) – Available off the require function©2012 LinkedIn Corporation. All Rights Reserved. LINKEDIN UED 21
    • 22. Asynchronous Module Definition©2012 LinkedIn Corporation. All Rights Reserved. LINKEDIN UED 22
    • 23. The AMD Standard define(moduleId, dependencies, function() {}) – Name this download “moduleId” [optional] – Before running, download & execute dependencies (array, [optional]) – Then run the callback function (“dependencies” are arguments) – If you depend on “require” or “exports”, they will work like their CommonJS counterparts©2012 LinkedIn Corporation. All Rights Reserved. LINKEDIN UED 23
    • 24. Harmony Modules in ECMAScript! Nested virtualization State isolation Dynamic loading Global namespace isolation Compilation hooks http://wiki.ecmascript.org/doku .php?id=harmony:modules_ex amples Some day©2012 LinkedIn Corporation. All Rights Reserved. LINKEDIN UED 24
    • 25. Let’s Talk INJECT©2012 LinkedIn Corporation. All Rights Reserved.
    • 26. In A Slide Inject is a Dependency Management Framework for the browser Supports CommonJS and AMD specifications Works cross-domain (CDNs) Does not require precompilation in order to function©2012 LinkedIn Corporation. All Rights Reserved. LINKEDIN UED 26
    • 27. For Libraries That Aren’t Inject “AMD” examples still work for browsers Telling the framework where files are differs The “run” command will be slightly different©2012 LinkedIn Corporation. All Rights Reserved. LINKEDIN UED 27
    • 28. ©2012 LinkedIn Corporation. All Rights Reserved. LINKEDIN UED 28
    • 29. Our Files inject.js – the main inject file (that’s all we need for now) program_cjs.js – load a “math” library, and add 2 + 3 program_amd.js – same thing, with AMD syntax math_cjs.js – exposes an “add” function for adding numbers math_amd.js – same thing, with AMD syntax©2012 LinkedIn Corporation. All Rights Reserved. LINKEDIN UED 29
    • 30. 1. Get Inject©2012 LinkedIn Corporation. All Rights Reserved.
    • 31. http://www.injectjs.com Download Inject (Big Yellow Button) Documentation and Howtos Source code Mailing List©2012 LinkedIn Corporation. All Rights Reserved. LINKEDIN UED 31
    • 32. 2. Build Site Structure©2012 LinkedIn Corporation. All Rights Reserved.
    • 33. Directory Structure<site_root>/js – inject.js – /modules/  program_amd.js  program_cjs.js  math_amd.js  math_cjs.js©2012 LinkedIn Corporation. All Rights Reserved. LINKEDIN UED 33
    • 34. program_*.js// program_cjs.jsvar math = require(math_cjs);alert(math_cjs: + math.add(2, 3));// program_amd.jsdefine([math_amd], function(math) { alert(math_amd:’ + math.add(2, 3));});©2012 LinkedIn Corporation. All Rights Reserved. LINKEDIN UED 34
    • 35. math_*.js// math_cjs.jsexports.add = function(a, b) { return a + b;};// math_amd.jsdefine(function() { return { add: function(a, b) { return a + b; } }});©2012 LinkedIn Corporation. All Rights Reserved. LINKEDIN UED 35
    • 36. 3. Add Inject, Call Program©2012 LinkedIn Corporation. All Rights Reserved.
    • 37. Inject’s Script Tag and Inject.run()<head> <script src="/js/inject.js"></script></head><body> <!-- ... --> <script type="text/javascript"> Inject.setModuleRoot(/js/modules); // run CommonJS Code... require.run(program_cjs); // math_cjs: 5 // ... or AMD Code require.run(program_amd); // math_amd: 5 </script></body>©2012 LinkedIn Corporation. All Rights Reserved. LINKEDIN UED 37
    • 38. ©2012 LinkedIn Corporation. All Rights Reserved. LINKEDIN UED 38
    • 39. INJECT API©2012 LinkedIn Corporation. All Rights Reserved.
    • 40. Inject.setModuleRoot Where do I find files? setModuleRoot(String) – String: a URL path where files can be found.  /js/modules  http://example.com/js/modules If using a CDN (Advanced) use a full URL©2012 LinkedIn Corporation. All Rights Reserved. LINKEDIN UED 40
    • 41. Inject.setExpires How long to store files? setExpires(integer) – Integer: how long in minutes to preserve the cache Built in localStorage module to improve caching Older items from Inject are automatically dropped to make room Inject.setExpires(0) can create a “dev” environment©2012 LinkedIn Corporation. All Rights Reserved. LINKEDIN UED 41
    • 42. Inject.reset The ultimate escape hatch Clears Inject’s localStorage Removes all in-JS memory of currently loaded items Acts as if it hasn’t seen a module yet©2012 LinkedIn Corporation. All Rights Reserved. LINKEDIN UED 42
    • 43. INJECT Advanced API©2012 LinkedIn Corporation. All Rights Reserved.
    • 44. Inject.addRule Change the Behavior of a Module addRule(Regex|String, Integer?, Object) – Regex|String: if the module matches the regular expression / string, any alterations in Object will be applied – Integer (optional): allows you to dynamically reorder the rules by assigning them weights – Object: a set of alterations to perform “Lock” a module’s identifier to a URL Turn on/off the automatic attachment of “.js” to module IDs when converted to a URL Rewrite the code before it is executed©2012 LinkedIn Corporation. All Rights Reserved. LINKEDIN UED 44
    • 45. addRule Lock a Module’s PathInject.addRule(module/path, { path: http://example.com/external/module.js});Inject.addRule(module/anotherPath, { path: ’/local_directory/library/module.js});©2012 LinkedIn Corporation. All Rights Reserved. LINKEDIN UED 45
    • 46. addRule Turn on/off the “.js” Suffix// module/path.jsInject.addRule(module/path, { useSuffix: true});// module/pathInject.addRule(module/path, { useSuffix: false});©2012 LinkedIn Corporation. All Rights Reserved. LINKEDIN UED 46
    • 47. addRule Alter the File (ie non AMD/CJS Code)// <= 0.4.0Inject.addRule(/^jquery$/, { path: /path/to/jquery.js, useSuffix: false, pointcuts: { after: function () { module.exports = jQuery.noConflict(); } }});©2012 LinkedIn Corporation. All Rights Reserved. LINKEDIN UED 47
    • 48. addRule Alter the File (ie non AMD/CJS Code)// >= 0.4.1Inject.addRule(/^jquery$/, { path: /path/to/jquery.js, useSuffix: false, pointcuts: { afterFetch: function (next, text) { next(null, [ text, module.exports = jQuery.noConflict(); ].join(n)); } }});©2012 LinkedIn Corporation. All Rights Reserved. LINKEDIN UED 48
    • 49. Inject.plugin Extend Functionality to non-JS Things plugin(String, Object, Object?) – String: an identifier for the plugin. Automatically creates an addRule() that matches modules beginning with “<string>!” – Object: this is the same object used in addRule() to modify a module – Object (optional): any functions placed in the 3rd parameter are made available under Inject.plugins.<string> An easy interface for addRule to handle non-JS files Inject comes with support for CSS, JSON, and Plain Text©2012 LinkedIn Corporation. All Rights Reserved. LINKEDIN UED 49
    • 50. plugin The “text” Plugin(function () { Inject.plugin(text’, { useSuffix: false, path: function (path) { return path.replace(/^text!s*/, ); }, pointcuts: { afterFetch: function (next, text) { next(null, [, var text = ", encodeURIComponent(text), ";, module.setExports(decodeURIComponent(text));, ].join() ); } } }, {});})();©2012 LinkedIn Corporation. All Rights Reserved. LINKEDIN UED 50
    • 51. ©2012 LinkedIn Corporation. All Rights Reserved. LINKEDIN UED 51
    • 52. Roadmap 0.4.1 Final – Robust plugin support – afterFetch non-blocking pointcuts 0.4.2 Librarian Release – Internal library upgrades: Link, Fiber, EasyXDM – Standardize testing framework 0.4.x Planned – localStorage on CDN side – Reduced code base (EasyXDM for IE7 only) – Coffeescript Plugin – Npm “install”-like functionality, global modules©2012 LinkedIn Corporation. All Rights Reserved. LINKEDIN UED 52
    • 53. INJECThttps://github.com/linkedin/inject©2012 LinkedIn Corporation. All Rights Reserved. LINKEDIN UED
    • 54. Useful Links http://www.stevesouders.com/blog/2009/04/27/loading-scripts- without-blocking/ http://dojotoolkit.org/documentation/tutorials/1.8/modern_dojo/ http://www.injectjs.com http://requirejs.org https://github.com/amdjs/amdjs-api/wiki/AMD http://www.commonjs.org©2012 LinkedIn Corporation. All Rights Reserved. LINKEDIN UED 54