Survive JavaScript - Strategies and Tricks
Upcoming SlideShare
Loading in...5
×
 

Survive JavaScript - Strategies and Tricks

on

  • 3,492 views

Getting started with JavaScript can be somewhat challenging. Especially given how fast the scenery changes. In this presentation I provide a general view of the state of the art. Besides this I go ...

Getting started with JavaScript can be somewhat challenging. Especially given how fast the scenery changes. In this presentation I provide a general view of the state of the art. Besides this I go through various JavaScript related tricks that I've found useful in practice.

survivejs.com is a companion site of the presentation and goes on further detail in various topics.

The original presentation was given at AgileJkl, a local agile conference held in Central Finland.

Statistics

Views

Total Views
3,492
Views on SlideShare
3,477
Embed Views
15

Actions

Likes
2
Downloads
16
Comments
0

1 Embed 15

https://twitter.com 15

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

CC Attribution-NonCommercial LicenseCC Attribution-NonCommercial License

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    Survive JavaScript - Strategies and Tricks Survive JavaScript - Strategies and Tricks Presentation Transcript

    • Survive JavaScriptStrategiesand TricksJuho VepsäläinenAgileJkl 2013
    • Whats in Store?Web Development StrategiesJavaScript TricksConclusion·How Did We Get HereWhere Are We NowWhere Are We Headed---·Node.jsDevelopment ToolsStructuring CodeFinding LibrariesTesting-----·
    • Web Development Strategies
    • Strategy for GoldfishesSource: HikingArtist.com (CC BY-NC-ND)
    • Strategy for the Rest of Us
    • How Did We Get Here
    • Ten Days to JavaScript1995 - Brendan Eichs ten days → MochaKnown as LiveScript till the marketing folks changed thenameEven though has Java in name, completely differentInfluence of Java 1.0 visible mainly in Math and TimemodulesPrototypal inheritance a lá SelfDynamic, flexible, lambdasScheme in disguise - See The Little JavaScripter byCrockford·······
    • A Bit of JavaScriptvarhelloAgileJkl=hello.bind(undefined,AgileJkl!);helloAgileJkl();functionhello(target){console.log(Hello+target);}//orcouldjustconsole.log(HelloAgileJkl!);//toavoidover-engineering!JAVASCRIPT
    • Web - From Documents to ApplicationsWeb as a Document PlatformImproved InteractivityWeb as an Application Platform·1995 - Brendan Eichs ten days1999 - ES3 (modern baseline), Mozilla established--·2005 - AJAX, dynamic loading (search for instance)2008 - RIP ES4, parts of HTML5 emerge, Chrome (V8)2009 - ES5, Chrome OS, Node.js---·2012 - HTML5 well supported (interesting JS APIs)-Source: Brendan Eich at Strange Loop 12
    • JavaScript Has TractionSource: Redmonk
    • CrockfordSource: superfluity (CC BY-NC-SA)
    • The Good Parts vs. The RestSource: Oльга + Haфaн (CC BY)
    • RecapJavaScript, an unlikely winnerLanguage of the webMore powerful than it seemsWeb isnt just about documents, now applications too····
    • Where Are We Now
    • Elements of Web Applications
    • Logic
    • JavaScript
    • CoffeeScriptCoffeeScript is a little language that compiles into JavaScript. Underneath that awkwardJava-esque patina, JavaScript has always had a gorgeous heart. CoffeeScript is an attempt toexpose the good parts of JavaScript in a simple way.The golden rule of CoffeeScript is: "Its just JavaScript". The code compiles one-to-one into theequivalent JS, and there is no interpretation at runtime. You can use any existing JavaScript libraryseamlessly from CoffeeScript (and vice-versa). The compiled output is readable and pretty-printed,passes through JavaScript Lint without warnings, will work in every JavaScript runtime, and tendsto run as fast or faster than the equivalent handwritten JavaScript.Latest Version: 1.6.2sudo npm install -g coffee-scriptOverviewCoffeeScript on the left, compiled JavaScript output on the right.# Assignment:number = 42opposite = truevar cubes, list, math, num, number, opposite, race, square,__slice = [].slice;TABLE OF CONTENTS TRY COFFEESCRIPT ANNOTATED SOURCE
    • Dart(/)Dart brings structure to web appengineering with a new language,libraries, and tools. Read about ournew M4 release!(http://news.dartlang.org/2013/04/core-libraries-stabilize-with-darts-new.html)News (http://news.dartlang.org/) TweetTweetSearch Docs Tools Resources Development
    • TypeScriptGet TypeScript NowTypeScript is a language for application-scale JavaScript development.TypeScript is a typed superset of JavaScript that compiles to plainJavaScript.Any browser. Any host. Any OS. Open Source.Starts from JavaScript, Ends withJavaScriptTypeScript starts from the syntax and semantics that millions of JavaScript developers knowtoday.learn play get it run it join in
    • And many othersaltJS
    • Markup
    • HTML
    • Jadedoctype 5html(lang="en")headtitle= pageTitlescript(type=text/javascript)if (foo) {bar()}bodyh1 Jade - node template engine#containerif youAreUsingJade<!DOCTYPE html><html lang="en"><head><title>Jade</title><script type="text/javascript">if (foo) {bar()}</script></head><body><h1>Jade - node template engine</h1>View DocumentationNode Template Engine
    • Mustache}Logic-less templates.Available in Ruby, JavaScript, Python, Erlang, PHP, Perl, Objective-C, Java, .NET, Android, C++, Go, Lua, ooc, ActionScript, ColdFusion, Scala,Clojure, Fantom, CoffeeScript, D, and for node.js.Works great with TextMate, Vim, Emacs, and Coda.The Manual: mustache(5) and mustache(1)Demo
    • HandlebarsHandlebars provides the power necessary to let you build semantic templateseffectively with no frustration.Mustache templates are compatible with Handlebars, so you can take a Mustachetemplate, import it into Handlebars, and start taking advantage of the extra Handlebarsfeatures.Download: 1.0.0-rc.3Download: 1.0.0-rc.3Download: runtime-1.0.0-rc.3Getting Started
    • TransparencyExamplesAssigning valuesAssigning valuesIterating over a listIterating over a listNested listsNested listsNested objectsNested objectsTransparency is a minimal template engine for jQuery. It maps JSONTransparency is a minimal template engine for jQuery. It maps JSONobjects to DOM elements with zero configuration.objects to DOM elements with zero configuration. Just call .render()Just call .render()CoffeeScript JavaScripthello=hello:"Hello!"hi: "<i>Hithere!</i>"span: "Goodbye!"$(.container).renderhelloJade HTML.container#hello.hispan
    • Styling
    • CSS
    • LESSWrite some LESS:@base: #f938ab;.box-shadow(@style, @c) when (iscolor(@c)) {box-shadow: @style @c;-webkit-box-shadow: @style @c;-moz-box-shadow: @style @c;}.box-shadow(@style, @alpha: 50%) when (isnumber(@alpha)) {.box-shadow(@style, rgba(0, 0, 0, @alpha));}.box {color: saturate(@base, 5%);border-color: lighten(@base, 30%);div { .box-shadow(0 0 5px, 30%) }}Compile to CSS:npm install -g lesslessc styles.less styles.cssversion 1.3.3changelogThe dynamic stylesheet language.LESS extends CSS with dynamic behavior such asvariables, mixins, operations and functions.LESS runs on both the server-side (with Node.jsand Rhino) or client-side (modern browsers only).overview   usage   language   function reference   source   about   try it now! FollowFollow
    • SASS$ gem install sass$ mv style.css style.scss$ sass --watch style.scss:style.cssAbout Tutorial Documentation Blog Try OnlineLatest Release: Media Mark (3.2.7)Whats New?DownloadEditor SupportDevelopmentSass makes CSS fun again. Sass is an extension of CSS3, adding nested rules, variables, mixins,selector inheritance, and more. It’s translated to well-formatted, standard CSS using the commandline tool or a web-framework plugin.Sass has two syntaxes. The most commonly used syntax is known as “SCSS” (for “Sassy CSS”), and isa superset of CSS3’s syntax. This means that every valid CSS3 stylesheet is valid SCSS as well. SCSSfiles use the extension .scss.The second, older syntax is known as the indented syntax (or just “.sass”). Inspired by Haml’sterseness, it’s intended for people who prefer conciseness over similarity to CSS. Instead of brackets
    • Twitter BootstrapBootstrap (./index.html)BootstrapSleek, intuitive, and powerful front-endframework for faster and easier webdevelopment.Download Bootstrap (assets/bootstrap.zip)
    • Zurb FoundationFeatures (grid.php) Add-ons (templates.php) Case Studies (case-jacquelinewest.php) Docs (docs) Training (training.php)Foundation (http://foundation.zurb.com)FoundationThe most advanced responsivefront-end framework in the world.Download Foundation 4 (download.php)10.9k stargazers(http://github.com/zurb/foundation)@foundationzurb(http://twitter.com/foundationzurb)
    • Data
    • DataUsually handled with a backend or external services(Disqus for comments for example)RESTful interfaces (client-side MVC)Local caching (localStorage ie.)Offline usage (replication, PouchDB)····
    • Big DataSource: infocux Technologies (CC BY-NC)
    • RecapLogics are violetMarkups are blueStyling is sweetAnd so is data
    • Where Are We Headed
    • EnlightenmentSource: michael.heiss (CC BY-NC-SA)
    • Source: Augie Schwer (CC BY-SA)
    • Source: letmehearyousaydeskomdeskom (CC BY-SA)
    • Shima thin often tapered piece of material (as wood, metal, orstone) used to fill in space between things (as for support,leveling, or adjustment of fit)Source: Merriam-Webster, esagor (CC BY-NC)
    • caniuse.comIndex TablesCan I use...Compatibility tables for support of HTML5, CSS3, SVG and more in desktop and mobile browsers.Latest update: Three new features added: Shadow DOM, WebP images & Intrinsic width & height (April 3, 2013)Search:border‑radius, WebGL, woff, etcCSS@font­face Web fontscalc() as CSS unit value2.1 selectorsCountersFeature QueriesFilter EffectsGenerated contentGradientsGrid LayoutHyphenationinline­blockMasksmin/max­width/heightoutlineposition:fixedRegionsHTML5Audio elementCanvas (basic support)Color input typecontenteditable attribute (basic support)Datalist elementdataset & data­* attributesDate/time input typesDetails & Summary elementsDownload attributeDrag and DropForm validationHTML5 form featuresinput placeholder attributeNew semantic elementsNumber input typeOffline web applicationsSVGInline SVG in HTML5SVG (basic support)SVG effects for HTMLSVG filtersSVG fontsSVG fragment identifiersSVG in CSS backgroundsSVG in HTML img elementSVG SMIL animationAll SVG featuresOtherasync attribute for external scriptsTOPSuggestions  Feed  TwitterImport stats FAQ Resources Embed564
    • Source: T.R.G. (CC BY-NC-SA)
    • Rise of the Mobile
    • AndroidSource: San Diego Shooter (CC BY-NC-ND)
    • Firefox OS, Jolla etc.
    • Source: Brian LeRoux (CC BY-NC-SA)
    • Native vs. HTML5Native apps still have their advantagesJS is a good alternative for prototypingAvailable technology keeps maturingAnd well likely see better platform support····
    • Web Architectures
    • Blog (Static Site)
    • JSter (Portal)
    • Future JSter?
    • Other ConsiderationsWhat belongs to server, what to client and why (businessgoals)Client-side MVC is not a silver bulletBasecamps experiences (hint: pushState, aggressivecaching)Synchronization, offline usage, skills, time, budget...Fashion. Techs come and goUp and coming? Mixed approaches. Examples: Meteor,Derby, mojito, rendr······
    • RecapWeb dev is as hard as you make itEspecially on the bleeding edgeFortunately a bit of tape fixes anythingMobile on the rise, native HTML5 apps not mainstream yetWeb architectures - from monoliths to distributed·····
    • JavaScript Tricks
    • Node.js
    • TrendsSource: Google Trends
    • Packages per YearPython: 29,720 packages / 22 years = 1351 packages / yearRuby: 54,385 packages / 18 years = 3022 packages / yearNode.js: 26,966 packages / 4 years = 6742 packages / year···Source: Gregg Gaines
    • Server Using Callbacksvarhttp=require(http);http.createServer(function(req,res){res.writeHead(200,{Content-Type:text/plain});res.end(HelloAgileJkl!n);}).listen(8000);JAVASCRIPTShort and sweetExpress is very popular for more complex cases··
    • Server Using EventStreamsvarhttp=require(http);vars=newhttp.Server();s.on(request,function(req,res){res.writeHead(200,{Content-Type:text/plain});res.end(HelloAgileJkl!n);});s.listen(8000);JAVASCRIPTViable alternative to callbacks at timesMore info at Node.js: Patterns and Opinions by @izs (theNode guy)··
    • RecapExcellent for prototypingStrong ecosystem thanks to NPMDevelops at a blistering pace···
    • Development Tools
    • Vim, Emacs, Sublime Text, WebStorm...
    • Chrome InspectorSee also Firebug·Source: Chrome DevTools
    • LiveReloadLiveReload 2 proudly presents…The Web Developer Wonderland(a happy land where browsers dont need a Refresh button)CSS edits and image changes apply live.CoffeeScript, SASS, LESS and others just work.Citizenship is granted through the Mac App Store.Windows permanent residency issues are being worked out,temporary stay already allowed.
    • JSLintclearRead the instructions.Set the options.Enjoy The Good Parts.Donate.The JavaScript Code Quality ToolEdition 2013-04-09Source// Paste quality code hereSee also JSHint·
    • jsFiddleRun Save TidyUp JSHint Login/Sign upNo‑Library (pure JS)onLoadTip JSFiddleFrameworks & ExtensionsFiddle OptionsExternal ResourcesLanguagesAjax RequestsExamplesLegal, Credits and LinksGittipKeyboard shortcuts?111HTMLJavaScriptCSSResultOthers: jsbin, jsdo.it, ...·
    • Cloud9 IDECloud9 IDE - Online IDEGive us a shout out: Share on twitter Share on Google Share on facebook Share on emailSign upSign outUsername or e‑mail Password Sign InKeep me signed inForgot password? Resend activation emailOr sign in instantly with:NEWS: The Changelog of March: Stability, Performance, FeaturesHey there! Over the past month we have worked very hard on improving the stability and performance of our service. In addition, we also worked onsome interface changes ...read the full article | see all articlesPricingFeaturesBlogCompanyCompany•Board Members•Jobs•Press•ContactNode.jsNode.js•Nodebits.com•NodeManual.orgSupportSupport•Status•DocumentationYour code anywhere, anytime...
    • RecapTraditional editors and IDEs are fineAdditional tooling available, use itFuture in the web?···
    • Structuring Code
    • The Anti-Pattern<scriptsrc=jquery-current.jstype=text/javascript></script><scriptsrc=sorttable.js type=text/javascript></script><scriptsrc=scripts.js type=text/javascript></script><scriptsrc=miniCalendar.js type=text/javascript></script>HTMLEach include has to be defined by handBrittle and prone to error, especially with large codebasesDoes not encourage to modularityHard to reuse····
    • Concatenate Scripts<scriptsrc=application.jstype=text/javascript></script> HTMLOld skool but worksLess overhead at HTMLStill, running into dependency order problem atconcatenationPossible to complement by loading scripts (ie. jQuery)from a CDNNevertheless a step forward·····
    • RequireJS and AMD + Bower<scriptdata-main="scripts/main"src="scripts/require.js"></script> HTMLdefine([jquery,./math],function($,math){return{//exportsvector:function(){...}};});JAVASCRIPTModular, asynchronous approachIncludes defineoverhead (possible to mimic Node.jsconvention, though)Optimizer resolves dependencies and creates build(loadable with Almond)Configuration complex at times····
    • Browserify + NPM<scriptsrc=application.jstype=text/javascript></script> HTMLvar$=require(jquery);varmath=require(./math);exports.vector=function(){...};JAVASCRIPTAllows to use Node.js module convention (CJS)Better yet allows to hook into NPM ecosystem!Still fairly bleeding edge···
    • RecapNo official module system yet (ES6?)Many alternatives (AMD, CJS etc.)browserify looks promising (NPM!)···
    • Finding Libraries
    • NPMSearch PackagesNODE.JS HOMEDOWNLOADABOUTNPM REGISTRYDOCSBLOGCOMMUNITYLOGOSJOBSNode Packaged ModulesTotal Packages: 28 067907 584 downloads in the last day9 157 954 downloads in the last week33 188 669 downloads in the last monthPatches welcome!Any package can be installed by using npminstall.Add your programs to this index by using npmpublish.Recently Updated0m jspmMost Depended Upon2740 underscoreCreate Account | Login
    • BowerBower componentsDiscover Bower (http://bower.io)componentsCheck out some of my otherprojectsFocus(https://github.com/sindresorhus/focus),JsRun(https://github.com/sindresorhus/sublime-jsrun), sublime-editorconfig(https://github.com/sindresorhus/editorconfig-sublime), GitHub-Notifier(https://github.com/sindresorhus/GitHub-Notifier), Pure(https://github.com/sindresorhus/pure),quora-unblocker(https://github.com/sindresorhus/quora-unblocker)screenfull.js (https://git…stringify-object (https:/…Featured componentsFullsc…APIwrap…String…anflight-storage (https://gi…spice.css (https://github…Latest componentsStore…JSONdataBasic…dry cssmin.js (https://github.co…angularjs-ordinal-filter …Hot componentsSuper…mini…select…Angul…Ordinal(https://github.com/sindresorhus/bower-components)
    • JSwikiJSwiki2 TweetTweet 59EditEditHi there! Welcome to jswiki.This wiki indexes libraries and resources available for JavaScript. In addition it provides some starting pointsfor newbies in form of Beginners Resources. In case you want to contribute, do take a look at Meta first forsome extra pointers. Happy hacking!IMPORTANT! jster.net is a spiritual successor of jswiki. There is more content but thesite is less of a wiki. jswiki will remain here as more of a communal alternative. Inaddition you might want to check out the following:JSwikiEssentialsMultimediaGraphicsDataUIUtilitiesDevelopmentApplicationsjsgamewiki MicrojsEveryJS JSDBJSPkg
    • JSterFollowFollow @jsterlibs@jsterlibsBlogCatalogAdd LibrarySign InFind a Javascript libraryJSter is a catalog of 1095 JavaScript libraries and tools for web development.Problems?Problems?
    • RecapNo need to just Google itPackage managers (esp. NPM) make your life easierAvoid NIH and use existing solutions···
    • Testing
    • Unit Testingassert(title(HELLOWORLD!)===HelloWorld!);assert(title(Helloworld!)===HelloWorld!);assert(title(hi)===Hi);assert(title()===undefined);functiontitle(s){returns&&s.split().map(capitalize).join();}functionassert(s){if(!s)thrownewError(Assertionfailed!);}JAVASCRIPTPopular alternatives: Jasmine (BDD), Mocha, QUnit·
    • Fuzz Testing//functiontotest,noteannotationvartitle=annotate(title,Returnsgivenstringinatitleformat.).on(is.string,function(s){returns&&s.split().map(capitalize).join();}).satisfies(is.string);//testinganinvariantfuzz(title,function(op,str){varparts=op(str).split();returnparts.map(fst).map(isUpper).filter(id).length==parts.length;});JAVASCRIPTUp and coming (hopefully)·Source: bebraw/annofuzz
    • Testlingtestling-cirun your browser tests on every pushwrite some testsUse the test runner you like best!The only thing your test runner needs to do is to produce TAP outputon console.log or process.stdout. Heres an example project usingmocha.You can also use tape to output TAP output in browsers and in node.Here is what a simple tape test looks like:var test = require(tape);var myCode = require(../my_code.js);test(make sure my code works, function (t) {t.plan(2);t.equal(myCode.beep(5), 555);
    • Travistravis-ci.orgBlogDocumentationEnglishFrançaisEspañolPortuguêsTravis CIA hosted continuous integration service for the open source community.Welcome to Travis CI #Travis CI is a hosted continuous integration service for the open source community. It is integrated with GitHub and offers first class support for:CC++ClojureErlangGoGroovyHaskellJavaJavaScript (with Node.js)Perl
    • Browserlinginteractive cross-browser testinghttp://3.0 3.5 3.6 4.0 5.0 6.07.0 8.0 9.0 10.0 11.0 12.013.0 14.0 15.0 16.0 17.0 18.019.0 nightlycreate account sign in
    • BrowserstackLive, Web-Based Browser TestingInstant access to all desktop and mobile browsers.Say goodbye to your setup of virtual machines and devices.Free TrialSign up for freeFull NameEmailPasswordNo credit cardNo credit cardrequired. We promise.required. We promise.Support Pricing Free TrialResources Sign inLive
    • Chaos MonkeySource: Jeff Atwood - Working with the Chaos Monkey
    • AB TestingSource: TheBusyBrain (CC BY)
    • RecapTest your JSBrowser differences bring their own challengeFuture in continuous integration (Travis and co.)Fail constantly to avoid failure····
    • Conclusion
    • ConclusionJS - the most valuable language you dont know yetA target for tool and language developmentNot without its quirks but still manageableThe most important language of this decade?····
    • Survive JS - The GuideSurvive JSHave you ever felt lost in the JavaScript jungle? If so, you are in the right place. The purpose of this guideis to provide you with sharp implements that help you survive and perhaps thrive even. Even seasonedJavaScript explorers might find a trick or two to apply in practice.As it is very possible I have not reached omnipotence yet, I encourage you to submit issues. This way wecan make the guide to serve you better.I am well aware there are other excellent resources out there. Of these I would like to mention EloquentJavaScript and JavaScript Garden in particular. I have listed various beginners resources over at JSwiki,the predecessor of JSter.Table of ContentsA Misunderstood Language? - What is the essence of JavaScript? Why is it relevant?Current State - What is the current state of JavaScript and the ecosystem?Language Features - What the language looks like? How to use it effectively?EditEditTweetTweet 00Table of ContentsSurvive JS
    • Thank You!twitter @bebrawwww www.nixtu.infogithub github.com/bebraw