[Slides from my 'Edge of the Web' workshop]
The web platform has evolved significantly over the last several years, giving developers more power than ever to create rich, interactive applications delivered via browsers. New capabilities in HTML, CSS and JavaScript paired with constantly updating browsers make it possible to do things on the web that used to be the exclusive domain of plugins and native apps. In this workshop, you’ll be introduced to some of the most powerful and useful techniques available to the modern web developer that will change the way you think about web app development.
The future of web app development is exciting, and these are the technologies that will underpin and drive that change. Don’t get left behind with IE8-era knowledge. Get ahead of the curve and master the edge of the web.
3. Hello, my name is…
@toddanglin
VP, Technology & Developer Relations
Telerik (a Progress Company)
4. AM
oBrowsers & Debugging
oNew web APIs
o Markup
o Media
o Storage
o Offline
PM
oModern JavaScript (ES6)
oModern CSS
o Styling
o Layouts
o Mobile & Media Queries
5. 1. Expand awareness of modern web
technologies
2. Introduce techniques for using modern web
3. Enhance knowledge of existing web
technologies
4. Provide practical “next steps” on modern
web journey
29. StatCounter NetMarketShare
Records data from 3 million websites Analyzes data from 40 thousand websites
Analyzes 17.5 billion page views per month Analyzes 160 million unique visits per month
Make no adjustments or weightings other than
removing bot activity and pre-rendering
Applies country weightings according to CIA
Internet Traffic data. For example, if Brazil
accounts for 4% of global traffic but only 2% of
NetMarketShare data, the results are doubled
Is independent and has no commercial partners
Is a commercial company with partners paying
for data
Reports are based on page views Reports are based on daily unique visitors
Source: http://www.sitepoint.com/browser-trends-april-2015-statcounter-vs-netmarketshare/
42. Selectors (2.1)
position:fixed
7.0 LocalStorage
DragDrop API
JSON
querySelector
8.0
Video
Audio
WOFF
SVG
Canvas
Geolocation
Semantic Tags
Lots of CSS3
9.0
XHR2
Web Workers
Web Sockets
IndexedDB
History API
File API
CORS
Blob URLs
Typed Arrays
Defer/Async
Form Validation
New Input Types
Offline App Cache
Much more CSS3
10.0
43. Selectors (2.1)
position:fixed
7.0 LocalStorage
DragDrop API
JSON
querySelector
8.0
Video
Audio
WOFF
SVG
Canvas
Geolocation
Semantic Tags
Lots of CSS3
9.0
XHR2
Web Workers
Web Sockets
IndexedDB
History API
File API
CORS
Blob URLs
Typed Arrays
Defer/Async
Form Validation
New Input Types
Offline App Cache
Much more CSS3
10.0
3D Transforms
Web Crypto
CustomEvent
X-Doc Messaging
DeviceOrientation
FileReader API
HTTP/2
CSP 1.0
SVG effects
Touch events
Video tracks
ES6
getUserMedia
Templates
Picture
Meter
PointerLock API
ASM.js
Gamepad API
Date/time inputs
…
Edge (13)
49. X X X X X
X X X
X X
X X X
X X
Only use features
natively available in all
target browsers
50. X X X X X
X X X
X X
X X X
X X
Only use features
either natively available
OR available via
JavaScript polyfill
X X
51.
52. X X X X X
X X X
X X
X X X
X X
Only use features
available in target
browsers AND design
alternate experience
for other browsers
X X
X X X
X X
22:31
77. data-*
Valid approach to storing data in HTML
<!--Store values in data-* attributes-->
<div id="mydiv" data-key="26" data-name="My product name">
...
</div>
<!--Access values with JavaScript-->
var key = mydiv.getAttribute("data-key")
//OR
var key = mydiv.dataset.key
support: IE9, FF3.5, Safari, Chrome, Opera
80. <video src="clip.mp4" controls type="video/mp4">
<object classid="...">
<param name="flashvars" value="file=clip.mp4" />
<param name="movie" value=“player.swf" />
<embed src="player.swf” type="application/x-shockwave-
flash” flashvars="file=clip.mp4" />
Your browser does not support video
</object>
</video>
support: IE9, FF3.6, Safari, Chrome, Opera
22:31
81. oVideo for plug-less mobile
devices
oEliminate dependencies
on Flash/Silverlight (future
proofing)
22:31
82. tag: time, date, search, email, etc.
Web Forms 2.0 HTML5 Forms
<form>
<input type="email" autofocus="autofocus"
placeholder="Enter your email" />
</form>
support: Safari, FF4*, Chrome, Opera
83. oHTML: Required, Type, Pattern
oJS: checkValidity()
oCSS: :invalid, :valid, :required
<form>
<input type="email" placeholder="Enter your email" required title="Please
enter a valid email address" />
<input type="submit" value="Go" />
</form>
84. via A List Apart (bit.ly/html5validation)
22:31
98. easy drag & drop for any HTML element
<!-- Make an HTML element draggable -->
<div id=“myDiv” draggable=“true”>...</div>
//Handle the DnD events, such as Drop
function onDrop(e){
//e.target is the current target element
if(e.stopPropigation) e.stopPropigation(); //Prevent redirect
//Do something with payload
return false;
}
support: IE9, FF, Safari, Chrome, Opera
103. access to local file system & data streaming
var file = e.dataTransfer.files[0],
reader = new FileReader();
reader.onload = function (event) {
var dataUrl = event.target.result;
};
reader.readAsDataURL(file);
.readAsBinaryString(file);
.readAsText(file);
.readAsArrayBuffer(file);
support: IE10, FF4, Chrome, Opera 11.1
119. api: openDatabase
db = openDatabase("html5demos", "1.0", "HTML 5 Database API example",
200000);
if (db) {
db.transaction(function(tx) {
tx.executeSql("CREATE TABLE IF NOT EXISTS tweets (id REAL UNIQUE,
text TEXT, created_at TEXT, screen_name TEXT,
mention BOOLEAN)", [], callback);
});
}
db.transaction(function (tx) {
tx.executeSql('SELECT * FROM tweets WHERE mention = ? AND id > ? ORDER
BY id DESC', [mention, latest], callbackFunc);});
support: Safari, Chrome, Opera
“This specification has reached an impasse: all
interested implementors have used the same
SQL backend (Sqlite), but we need multiple
independent implementations to proceed along
a standardisation path.”
–W3C
120. JavaScript API for indexed local storage
var request = window.indexedDB.open("CandyDB",
"My candy store database");
request.onsuccess = function(event) {
var db = event.result;
if (db.version != "1") {
// User's first visit, initialize database.
...
}
}
support: IE9*, FF4, (Chrome)
127. tag: <html manifest="html5demo.manifest">
MIME type: text/cache-manifest
CACHE MANIFEST
# Files you want cached for your app to work offline
myLogo.jpg
//Interacting with cache
window.applicationCache.update();
alert(window.applicationCache.status);
support: FF3.5, Safari, Chrome, Opera 10.6
130. Service Workers
Superior to AppCache by providing programmatic control offline
cache. Background thread for web apps with control over network
requests.
155. NATIVE LOOPS
$.each(arr, function (i) {i / 2;});
BAD
arr.forEach(function (i) {i / 2;});
BETTER
var i = 0, len = arr.length;
for (i = 0; i < len; i += 1) {
i / 2;
}
BEST*
Prove It
161. function doInitStuff(){
var user = "Todd";
}
function loadSomething(){
if (user == "Todd") ...
}
function handleButtonClick(){
...
}
function harlemShake(){
...
}
yourFile.js
162. var user = "";
function doInitStuff(){
user = "Todd";
}
function loadSomething(){
if (user == "Todd") ...
}
function handleButtonClick(){
...
}
function harlemShake(){
...
}
yourFile.js
163. var [window].user = "";
function [window].doInitStuff(){
user = "Todd";
}
function [window].loadSomething(){
if (user == "Todd") ...
}
function
[window].handleButtonClick(){
...
}
function [window].harlemShake(){
...
yourFile.js
164. var app = (function(){
var _name = "Todd";
return{
sayHello: function(){
alert(_name);
}
}
}());
app.sayHello();
22:31
BEST(ISH)
165. var app = (function(){
var _name = "Todd";
return{
sayHello: function(){
alert(_name);
},
sayGoodbye: function(){
alert(_name);
}
}
}());
22:31
BEST(ISH)
Your
“Public” API
166. SUPER PATTERN
(function(window,$,c){
var _private = "Todd";
function privateClass(){}
function myWidget(){}
myWidget.doSomething = function(){};
window.myWidget = myWidget;
}(window,jQuery,console));
Immediately Invoked Function Expressions (IIFE) +
Global Imports + [Prototype]
Prove It
175. My Awesome Page
Copyright Fo'eva
Lorem ipsumy samplish
jibber jabbish text only
meant to serve as a
placeholder, and much like
Pi, should never repeat or
be read much beyond the
first few characters.
176. function doSomething{
...
var $list = $("body").append("<ul>");
for(var i = 0; i < 10; i++){
$list.append("<li>"+ i +"</li>")
}
}
22:31
BAD
177. function doSomething{
...
var $domChunk = $("<ul>");
for(var i = 0; i < 10; i += 1){
$domChunk.append("<li>"+ i +"</li>");
}
$("body").append($domChunk);
}
22:31
BETTER
178. DOM SPEED WITH
STRINGS & INNERHTML
function doSomething{
...
var domString = "<ul>";
for(var i = 0; i < 10; i += 1){
domString += "<li>"+ i +"</li>";
}
domString += "</ul>"
$("body")[0].innerHTML = domString;
}
Prove It
179. <script type="text/x-kendo-template" id="tmp">
<ul>
#for(var i = 0; i < data.length; i += 1){#
<li>#= data[i] #</li>
#}#
</ul>
</script>
function doSomething(){
var myData = [1,..,10];
var template = kendo.template($("#tmp").html());
$("body").append(template(myData));
}
22:31
BEST
Prove It
183. o break
o case
o class
o catch
o const
o continue
o debugger
o default
o delete
o else
o export
o extends
o finally
o for
o function
o if
o import
o in
o instanceof
o let
o new
o return
o super
o switch
o this
o throw
o try
o typeof
o var
o while
o with
o yield
184. o arrows
o classes
o enhanced object literals
o template strings
o destructuring
o default + rest + spread
o let + const
o iterators + for..of
o generators
o unicode
o modules
o module loaders
o map + set + weakmap +
weakset
o proxies
o symbols
o subclassable built-ins
o promises
o math + number + string + array
+ object APIs
o binary and octal literals
o reflect api
o tail calls
214. /*These two rules do the same thing*/
@media all and (min-width:500px) { … }
@media (min-width:500px) { … }
/*Multiple conditions*/
@media screen and (min-width: 600px) and (max-width: 900px) {
.class {
background: #333;
}
}
233. Good Bye. Adios. Auf Wiedersehen.
E: anglin@telerik.com
T: @toddanglin
S: slideshare.net/toddanglin
Notes de l'éditeur
The web platform has evolved significantly over the last several years, giving developers more power than ever to create rich, interactive applications delivered via browsers. New capabilities in HTML, CSS and JavaScript paired with constantly updating browsers make it possible to do things on the web that used to be the exclusive domain of plugins and native apps. In this workshop, you’ll be introduced to some of the most powerful and useful techniques available to the modern web developer that will change the way you think about web app development.
Topics covered include:
Emerging browser capabilities for creating high performance, offline-enabled apps (Application Cache, Service Workers, Offline APIs, Web Storage)
Next generation of HTML UI component technology (Web Components, Shadow DOM)
Powerful new layout systems in CSS that eliminate the need for floats (Flexbox, Grid)
Techniques and frameworks for creating mobile-friendly, responsive layouts (Media Queries)
Exciting new language features in JavaScript (ES6) that improve code structure in large JavaScript apps
Key improvements in browsers and browser developer tools that are critical to the modern web developer (Evergreen, Browser Flags, Profiling, Debugging, Screen Emulation, Mobile Debugging)
The future of web app development is exciting, and these are the technologies that will underpin and drive that change. Don’t get left behind with IE8-era knowledge. Get ahead of the curve and master the edge of the web.
Bogus chart – based on “research” by Wiman & Meirhenry, and Edgar Dale 1960
Research since proven to be made-up. Still, fun slide and anecdotally true…
DEBUNKING:
http://www.willatworklearning.com/2006/05/people_remember.html
http://www.conversionrate.com.au/2008/06/16/retention-myth-people-remember-50-of-what-they-see-and-hear-and-only-10-of-what-they-read/
Talk about the major “platforms” for the web. Introduce the players.
WHATWG FAQs on Living Standard: http://wiki.whatwg.org/wiki/FAQ#What_does_.22Living_Standard.22_mean.3F
Trick question: Common answers will be the popular browsers.
Right answer: The browsers that YOUR users use (based on analytics)
Mobile browsers are just as important for today's web developer.
http://mashable.com/2010/04/13/mobile-web-stats/
CanIUse.com
IE 11 (versus 10):
Pointer Events
Flexbox
Viewpoint Units
xDoc Messaging
Full Screen API
CSS3 Border Images
WebGL*
dataset
CanIUse.com
IE 11 (versus 10):
Pointer Events
Flexbox
Viewpoint Units
xDoc Messaging
Full Screen API
CSS3 Border Images
WebGL*
dataset
Scores from HTML5Test.com (updated Oct 2013)
Sun Spider benchmark test: http://www.webkit.org/perf/sunspider/sunspider.html
Show off some HTML5 in action
This is not a question with a single correct answer. It all depends on your audience and strategy.
There are several general strategies for defining what is “usable” today.
Useful for adding HTML5 to both older browsers + new browsers that do not have a specific HTML5 feature
http://remysharp.com/2010/10/08/what-is-a-polyfill/
https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-browser-Polyfills
Strategy: Design for lowest common denominator, Enrich/Enhance as more capabilities are available
Image Source: http://www.flickr.com/photos/aaronolaf/833342657/
Strategy: Design for best case scenario (premium features), and gracefully remove features as resources are not available
Image Source: http://www.mbusa.com/mercedes/index
Modern adoption of HTML5 is done by checking for individual feature support, NOT by checking for specific browsers/browser versions. This helps you adopt as much of HTML5 as possible in a progressively optimistic manner.
http://www.modernizr.com/
http://www.modernizr.com
http://www.alistapart.com/articles/taking-advantage-of-html5-and-css3-with-modernizr/
Modernizr now ships with ASP.NET MVC 3
Important to define the scope and vastness of HTML5
Focusing on features most popular in use today by HTML5 developers. Sources:
http://css-tricks.com/poll-results-html5-features-in-use-on-production-sites/
http://css.dzone.com/articles/what-are-most-common-html5
Demo End Result Goal
Focusing on features most popular in use today by HTML5 developers. Sources:
http://css-tricks.com/poll-results-html5-features-in-use-on-production-sites/
http://css.dzone.com/articles/what-are-most-common-html5
http://www.javascriptkit.com/dhtmltutors/customattributes.shtml
http://html5doctor.com/html5-custom-data-attributes/
Two methods of access:
- Via Attributes (http://api.jquery.com/category/attributes/)
Via “dataset” (plug-in required today: http://www.orangesoda.net/jquery.dataset.html)
Chrome H.264 from MSFT: http://arstechnica.com/microsoft/news/2011/02/microsoft-offers-h264-plugin-for-chrome-queries-google-on-webm.ars
http://blogs.msdn.com/b/ie/archive/2011/02/01/html5-and-web-video-questions-for-the-industry-from-the-community.aspx
Chrome’s pull of H.264: http://arstechnica.com/web/news/2011/01/googles-dropping-h264-from-chrome-a-step-backward-for-openness.ars/
http://www.whatwg.org/specs/web-apps/current-work/multipage/states-of-the-type-attribute.html#states-of-the-type-attribute
http://www.html5laboratory.com/s/simple-html5-contact-form.html
Web Forms 2 (old spec – now Forms in HTML5): http://dev.w3.org/html5/web-forms-2/
http://www.whatwg.org/specs/web-apps/current-work/multipage/forms.html#forms
Defined input types: http://www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#the-input-element
Cross browser input types: http://net.tutsplus.com/tutorials/html-css-techniques/how-to-build-cross-browser-html5-forms/
Cross browser forms 2.0: https://github.com/westonruter/webforms2
Link to demo from A List Apart (good final cap demo on validation)
iOS varies the keyboard significantly on the iPhone depending on the input type
Shown: iOS5 (not available in iOS4)
http://diveintohtml5.org/geolocation.html
Spec: http://dev.w3.org/geo/api/spec-source.html
Only lat, long, acc are guranteed. Other values might be available, including altitude, altitudeAccuracy, heading, speed
Can force maximum age for cached geolocation objects
Can handle errors and make repeat location calls using navigatior.geolocation.watchPosition(successCallback, errorCallback, {maximumAge:time})
Google Maps API v3 Reference: http://code.google.com/apis/maps/documentation/javascript/basics.html
(Free to use on all apps that are free to consumers – no API keys needed)
http://html5demos.com/storage
Tutorial: http://html5tutorial.net/tutorials/working-with-html5-localstorage.html
Fallback for older browsers:
http://amplifyjs.com/api/store/
Same Origin Policy for JS security
https://developer.mozilla.org/en/Same_origin_policy_for_JavaScript
Focusing on features most popular in use today by HTML5 developers. Sources:
http://css-tricks.com/poll-results-html5-features-in-use-on-production-sites/
http://css.dzone.com/articles/what-are-most-common-html5
Example source: https://css-tricks.com/modular-future-web-components/
Example source: https://css-tricks.com/modular-future-web-components/
WebSql is not proceeding: http://dev.w3.org/html5/webdatabase/
State of web local storage: http://rethink.unspace.ca/2010/5/10/the-state-of-html5-local-data-storage
Replacement Tech is IndexedDB:
http://dvcs.w3.org/hg/IndexedDB/raw-file/tip/Overview.html
Syncing back to a server database: http://stackoverflow.com/questions/1744522/best-way-to-synchronize-local-html5-db-storage-with-a-server
PersistenceJS: https://github.com/zefhemel/persistencejs
Google Web Stroage Portability Layer: http://google-opensource.blogspot.com/2009/05/web-storage-portability-layer-common.html
Kills Google Gears
http://www.w3.org/TR/IndexedDB/
https://developer.mozilla.org/en/IndexedDB
http://www.html5rocks.com/tutorials/indexeddb/todo/
Good comparison by Mozilla to former WebDatabase approach: http://hacks.mozilla.org/2010/06/comparing-indexeddb-and-webdatabase/
Example code for .NET WebSockets:
http://www.undisciplinedbytes.com/2010/06/html-5-c-web-sockets-server-and-asp-net-client-implementation/
Online demo: http://websocket.org/echo.html
Opera on Sockets:
http://my.opera.com/core/blog/websockets
Sockets disabled by default in FF and Opera: http://annevankesteren.nl/2010/12/websocket-protocol-vulnerability
Enabling sockets in Opera 11: opera:config#UserPrefs|EnableWebSockets
Enabling sockets in FF4: about:config -> network.websocket.override-security-block;true
IE9 can do WebSockets via a prototype Silverlight hack: http://html5labs.interoperabilitybridges.com/prototypes/available-for-download/websockets
Limits: http://html5labs.interoperabilitybridges.com/media/2311/readme.htm
Sockets vs. traditional polling performance: http://soa.sys-con.com/node/1315473
3rd party sockets solution for older browsers:
http://html5demos.com/offlineapp
http://diveintohtml5.org/offline.html
http://html5doctor.com/go-offline-with-application-cache/ (Good practical tips)
Inspect appcache in Chrome: chrome://appcache-internals/
Stephen Walther on using ASP.NET to serve Cache manifest: http://stephenwalther.com/blog/archive/2011/01/26/creating-html5-offline-web-applications-with-asp-net.aspx
Fix IIS Express manifest type: http://www.danielroot.info/2010/07/how-microsofty-writes-ipad-apps.html
C:\Users\{YOU}\Documents\IISExpress\config\applicationHost.config
Comment out the .manifest mime type (sorry ClickOnce!)
Add the following line: <mimeMap fileExtension=".manifest" mimeType="text/cache-manifest" />
Can also override in IIS7+ config (integrated pipeline):<system.webServer>
<staticContent>
<mimeMap fileExtension=".manifest" mimeType="text/cache-manifest" />
</staticContent>
</system.webServer>
Application Cache API: http://www.w3.org/TR/html5/offline.html#application-cache-api
Compatibility updated May 2015
AGENDA:
- Why JavaScript? Why?!
- Most Common JS Problems
- TIPS
- Future of JavaScript
JavaScript uses syntax influenced by that of C. JavaScript copies many names and naming conventions from Java, but the two languages are otherwise unrelated and have very different semantics. The key design principles within JavaScript are taken from the Self and Scheme programming languages.
http://en.wikipedia.org/wiki/JavaScript
NOTES:
History
Evolution
The IE Connection (IE6 memory)
Modern JS Engines
BOTTOM LINE: Only Cross Platform Language Solution
Netscape also wanted a lightweight interpreted language that would complement Java by appealing to nonprofessional programmers, like Microsoft's VB
Credit: Brendan Eich via Wikipedia
Source: http://www.jwz.org/blog/2010/10/every-day-i-learn-something-new-and-stupid/#comment-1021
Brendan further said that JavaScript saved the world from VBScript
http://www.jwz.org/blog/2010/10/every-day-i-learn-something-new-and-stupid/#comment-1049
Java is to JavaScript
AS
Car is to Carpet
Netscape was going to release JavaScript as “LiveScript.” Last minute change produced JavaScript.
HOW DID JAVASCRIPT BECOME UBIQUITOUS?
Netscape shipped first in Netscape 2
Microsoft support added in IE3 (“JScript”)
Other environments adopted JavaScript-like script languages: ActionScript (Flash), PDFs, Qt
Contributing factors:
New JS engines (V8)
CPU speed (more local processing power)
Better debugging tools
Better understanding of language (closures, patterns, functional programming, JSLint)
Chrome is 10x faster than IE7 (IE6 too old to test)
Used crude relative test: http://jsbenchmark.celtickane.com
http://geekmontage.com/firefox-vs-chrome-vs-ie/
http://www.codinghorror.com/blog/2007/07/the-principle-of-least-power.html
The Principle of Least Power
jQuery built for convenience, not for performance.
PERF PROOF: http://jsperf.com/id-vs-class-vs-tag-selectors/46
Note: This in general is applicable to native JavaScript methods too, like document.getElementById() not limited to jQuery only objects DOM lookups are slow especially if DOM is huge.
Instead of this:
$('#test').bind('click', function() { /**/ });
$('#test').css('border', '1px solid #999');
Better use jQuery Method chaining:
$('#test').bind('click', function() {/**/ })
.css('border', '1px solid #999');
Or cache jQuery object:
var $test = $('#test');
$test.bind('click', function() {/**/ });
$test.css('border', '1px solid #999');
(Performance comparison here: http://jsperf.com/jquery-chaining/12) (~+30% here, but it stacks on each additional method call)
PRO TIP CONVENTION: Name jQuery variables with $ (ie $myObject)
PERF TEST: http://jsperf.com/caching-jquery-objects-perf
http://jsbin.com/udizam/2
PERF TEST: http://jsperf.com/for-vs-foreach-vs-each/3
- Caching the array length improves perf by about 15% (http://jsperf.com/for-vs-foreach-vs-each/24)
- Technically a reverse (count down) for loop is faster (15%) than count-up loop, but much harder to read/use
Global variables pollute the JS app and are slower to use in code. Harder to be a good JS "neighbor" with global variables (collide with other JS code).
Better to use local variables, cached variable, or closures
Global memory garbage collecting problem example: http://fiddle.jshell.net/toddanglin/EhEBM/3/show/light/
Pattern sometimes referred to as: MODULE EXPORT
http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth
BE CAREFUL WITH CLOSURES: Most common source of memory leaks in modern apps
https://developers.google.com/speed/articles/optimizing-javascript
Circular Reference Memory Leaks: http://blogs.msdn.com/b/ericlippert/archive/2003/09/17/53028.aspx
Pattern sometimes referred to as: MODULE EXPORT
http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth
BE CAREFUL WITH CLOSURES: Most common source of memory leaks in modern apps
https://developers.google.com/speed/articles/optimizing-javascript
Circular Reference Memory Leaks: http://blogs.msdn.com/b/ericlippert/archive/2003/09/17/53028.aspx
PERF TEST: http://jsperf.com/prototype-vs-closures/20
Explanation of term: http://benalman.com/news/2010/11/immediately-invoked-function-expression/
Suppose you develop a widget. The widget has a number of axillary classes. If you just define them globally they will pollute the global window class, meaning they will be available from everywhere. Instead consider the following definition:
(function (window) {
function classA () {}
function classB () {}
function myWidget () {}
myWidget.prototype.method1 = function ()
{
}
window.myWidget = myWidget;
}) (window, undefined);
This is the pattern which jQuery follows. Now the only available global definition will be of myWidget. classA and classB remain hidden in the anonymous function. If you look closely in the definition, you will see the that window and undefined are passed to the anonymous function. Passing anonymous guaranties that undefined will be available in the scope of this function and will prevent you from someone who accidentally did something like:
undefined = true;
before your function. Also, if you use some minifier, it will replace all occurrences of window with some shorter name. Of course you can pass as much params as you wish, thus assuring that these objects exist in the scope of your anonymous function.
- Binding to delegates is less brittle, easier to avoid memory leaks
- Pub/Sub is super flexible, less coupling
The scope of an inline event bind is GLOBAL!
Inline event handlers can also cause memory leaks in IE: https://developers.google.com/speed/articles/optimizing-javascript
Old jQuery syntax: .delegate
Every time you need to dispose a DOM element, make sure you unbind all of its events, unless you want to come up with a memory leak.
Whenever you bind an event handler to an event, you tell the processor to allocate memory for it. The more event handlers you have running at the same time, the more memory you are using. This is why it's important to unbind or detach your event handlers soon as you no longer need them.
http://www.learnjquery.org/newsletter/Tutorial-3-jquery-events.html
Event listening PUB/SUB
Reducing the time spent changing the DOM improves perf. Using templates improves readability/maintainability.
Instead of this:
var $list = $('#mylist').append('<ul>');
for (var i = 0, l = itemlist.length; i < l; i++) {
$list.append('<li>' + itemlist[i] + '</li>');
}
better this:
var $list = $('<ul>');
for (var i = 0, l = itemlist.length; i < l; i++) {
$list.append('<li>' + itemlist[i] + '</li>');
}
$('#mylist').append($list);
(Performance comparison here: http://jsperf.com/jquery-dom-manipulation/3) (up to x5 in this case)
PERF TEST: http://jsperf.com/jquery-dom-manipulation/4
When you want to dynamically build html, prefer string concatenation like:
var html = ’<p>some paragraph</p>’;
html += ‘<p>another paragraph</p>’;
$(“#placeHolder”).html(html);
over DOM object creation and appending/prepending like:
var p1 = document.createElement('p');
p1.innerHTML = "some paragraph";
document.body.appendChild(p1);
var p2 = document.createElement('p’);
p2.innerHTML = "another paragraph";
document.body.appendChild(p2);
assigning directly to the innerHTML proves to be the fastest method for html creation.
Common Examples: RequireJS, CommonJS
Applications of any size are painful to manage without a module pattern.
ES6 Comparison: http://es6-features.org/
JSLint – by Douglas Crockford
Code quality tool for JavaScript
http://www.jslint.com/
Before CSS:
Styles were mixed with HTML tags (difficult to update, difficult to read)
Layout was defined with HTML tags (poor semantic use of tags)
CSS exists to separate styling and layout decisions from structural meaning of underlying document
*Separation of concerns to a degree
CSS rules often tend to create dependencies on HTML
Other benefits of CSS:
Performance (caching of CSS rules)
Semantic HTML
Peter Griffin CSS cartoon
Extensions for CSS2.1
Add functionality, refine definitions
New CSS3 features
CSS3 principles
Show example of CSS3 in action
List of all CSS properties: http://meiert.com/en/indices/css-properties/
http://www.w3.org/Style/CSS/current-work
http://www.w3.org/TR/2010/WD-css-2010-20101202/#css3
CSS3’s evolutionary approach
Microsoft is focusing primarily on adding product support at the Candidate Recommendation stage
Review status of various CSS3 proposed specs: http://www.w3.org/Style/CSS/current-work
Updated: Oct 2012
Microsoft Extensions: http://blogs.msdn.com/b/ie/archive/2008/09/08/microsoft-css-vendor-extensions.aspx
Vendor specific prefixes: http://reference.sitepoint.com/css/vendorspecific
CSS Selectors over time (1, 2, 3) - As of Nov 2011
@font-face was first proposed for CSS2 and has been implemented in Internet Explorer since version 5
IE relied on proprietary Embedded Open Type (.eot)
Old school solutions involved things like sIFR (http://www.mikeindustries.com/blog/sifr/)
Modern browsers finally support TTF and OTF + Most support new WOFF (exception is Safari)
Resources:
http://www.css3.info/preview/web-fonts-with-font-face/
http://www.alistapart.com/articles/cssatten