html, css & javascript architecture (extended version) - jan kraus

69
HTML, CSS & Javascript Architecture In a little bit bigger projects… v2

Upload: women-in-technology

Post on 22-Jan-2018

888 views

Category:

Technology


4 download

TRANSCRIPT

Page 1: HTML, CSS & Javascript Architecture (extended version) - Jan Kraus

HTML, CSS & JavascriptArchitectureIn a little bit bigger projects…

v2

Page 2: HTML, CSS & Javascript Architecture (extended version) - Jan Kraus

Jan Kraussenior frontend dev / creativestyle

Page 3: HTML, CSS & Javascript Architecture (extended version) - Jan Kraus

Part 1:

● Introduction● Coding guidelines● Servers● Tools & automatization● Starter templates● Responsive web design

Schedule

Part 2:

● Git & team work● Frameworks & libraries● Modular CSS: SMACSS, BEM● Javascript patterns● Coding challenge, Q&A

Page 4: HTML, CSS & Javascript Architecture (extended version) - Jan Kraus

A bigger project

● More than one frontend developer○ sometimes more than 1 team

● Multiple & different page types● Long term development goal● Responsive● Pure frontend or framework based solution

Page 5: HTML, CSS & Javascript Architecture (extended version) - Jan Kraus

Architecture

● Technology stack (frameworks)● Code organization● Coding guidelines● RWD

○ fluid vs. adaptive○ Mobile first vs. desktop first

● Icons system / images● Performance● Workflow

Page 6: HTML, CSS & Javascript Architecture (extended version) - Jan Kraus

Technology stack

● Backend frameworks○ Rails

■ assets pipeline○ Symfony

■ assetic○ Node.js,

■ Express, Meteor, Sails

● Frontend frameworks○ jQuery, Bootstrap,○ Backbone○ Angular, Ember, React

Page 7: HTML, CSS & Javascript Architecture (extended version) - Jan Kraus

● Maintain simple & clean structure for your code○ keep your code separated in assets folders

■ javascripts■ css / sass■ images■ fonts■ other stuff

● look for best practices for your framework● organize in modules instead by type

Code organization

Page 8: HTML, CSS & Javascript Architecture (extended version) - Jan Kraus

● don’t mix spaces & tabs○ I suggest to configure your editor to indent everything with 2 spaces○ but this is never ending war ;-)○ use good code editor

■ webstorm / phpstorm is quite powerful

● maintain clean & usable code○ comment well○ keep good variable names○ use consistent naming convention

● UTF-8 everywhere○ <div class="♫">

Coding guidelines

Page 9: HTML, CSS & Javascript Architecture (extended version) - Jan Kraus

HTML guidelines

● keep the code well formatted● use html5 doctype

○ occasionally check it with W3C validator

● keep all tags lowercase● wrap all attributes in double quotes● try to write semantic html

○ but don’t overdo with html5 semantic tags○ good reference at http://html5doctor.com/

● keep in mind accessibility○ learn about aria tags

Page 10: HTML, CSS & Javascript Architecture (extended version) - Jan Kraus

● keep the code well formatted● don’t rely on using ID-selectors for styling● use lowercase-class-names

○ write semantic class names○ separate with hyphens○ unless you consider using BEM / SMACSS

● avoid long selectors○ especially watch out for nesting in sass○ learn & understand how CSS cascade works○ avoid using !important

CSS guidelines - selectors

Page 11: HTML, CSS & Javascript Architecture (extended version) - Jan Kraus

● use shorthand properties○ padding: 10px 20px;

● don’t overuse -vendor-prefixes too much○ use autoprefixer○ they need to come before standard property

● try to avoid using pixel units everywhere○ learn about rems

● use #hex colors & rgba when wants opacity

CSS guidelines

Page 12: HTML, CSS & Javascript Architecture (extended version) - Jan Kraus

CSS guidelines

● keep media-queries close to relevant sections● separate bigger sections with block comments● organize code into meaningful sections

○ don’t write everything in the bottom○ find the “right place”

Page 13: HTML, CSS & Javascript Architecture (extended version) - Jan Kraus

SASS guidelines

● avoid nesting selectors○ or try to keep it up to 2-3 levels

■ or really, avoid!

● use sass @imports to organize your css code○ start name of imported partial with underscore

■ _grid.scss, _config.scss○ organize into components, modules, shared etc..

● use variables!○ at least for colors & media-query breakpoints

Page 14: HTML, CSS & Javascript Architecture (extended version) - Jan Kraus

Javascript guidelines

● keep the code well formatted● make sure you understand basics concepts of Javascript● use single quotes for strings● always use expanded blocks syntax

○ if (condition) { }

● use semicolons;● var camelCase your variable & function names● ModuleNames should start from capital letter

Page 15: HTML, CSS & Javascript Architecture (extended version) - Jan Kraus

Javascript guidelines

● use JSHint or ESLint to catch your errors● learn couple useful module patterns

○ jQuery plugin○ http://addyosmani.com/resources/essentialjsdesignpatterns/book/○ http://www.adequatelygood.com/JavaScript-Module-Pattern-In-Depth.html

● learn about ES6

Page 16: HTML, CSS & Javascript Architecture (extended version) - Jan Kraus

Immediately Invoked Function Expression

(function($, window, document) { // The $ is now locally scoped

// Listen for the jQuery ready event on the document $(function() { // The DOM is ready! });

// The rest of the code goes here!

}(window.jQuery, window, document));// The global jQuery object is passed as a parameter

Page 17: HTML, CSS & Javascript Architecture (extended version) - Jan Kraus

Revealing module pattern

var MyModule = (function(window, undefined) {

var myState = 0;

function initialize() {

console.log('Module initialized...');

}

function setState(data) {

state = data;

}

return {

init: initialize,

someOtherMethod: myOtherMethod

};

})(window);

MyModule.init(); // logs “Module initialized…”

MyModule.setState(3);

Page 18: HTML, CSS & Javascript Architecture (extended version) - Jan Kraus

jQuery plugin

;(function ( $, window, document, undefined ) {

var pluginName = "myPluginName",

defaults = {

propertyName: "value"

};

// The actual plugin constructor

function Plugin( element, options ) {

this.element = element;

this.options = $.extend( {}, defaults, options) ;

this._defaults = defaults;

this._name = pluginName;

this.init();

}

Plugin.prototype.init = function () {

// Place initialization logic here

};

$.fn[pluginName] = function ( options ) {

return this.each(function () {

if ( !$.data(this, "plugin_" + pluginName )) {

$.data( this, "plugin_" + pluginName,

new Plugin( this, options ));

}

});

}

})( jQuery, window, document );

Page 19: HTML, CSS & Javascript Architecture (extended version) - Jan Kraus

jQuery guidelines

● don’t abuse $(selector)○ remember to cache references to object○ keep prefix of your variable with $ to indicate its a jquery object

■ eg. $container = $('.container');

● consider using custom class as hooks for your events○ $('.js-button-submit')

● when binding events, preffer using .on()○ Avoid anonymous functions for debugging○ Use custom namespace for events○ Use delegation

Page 20: HTML, CSS & Javascript Architecture (extended version) - Jan Kraus

jQuery guidelines

● don’t put everything in $.ready function● use $.ajax instead of $.get, $.post methods● use Promise syntax for handling responses

○ $.ajax({ … })■ .done(successHandler)■ .fail(errorHandler)

● don’t use jQuery animations● avoid CSS changes via jQuery

○ prefer class toggling

Page 21: HTML, CSS & Javascript Architecture (extended version) - Jan Kraus

jQuery guidelines

● use jquery 2.x○ unless IE8

● load it from external CDN for caching benefits● don’t use too many jQuery plugins

○ check size○ check github page for issues

● think twice before using jQuery UI● bootstrap JS relies on jquery● http://gregfranko.com/jquery-best-practices/

Page 22: HTML, CSS & Javascript Architecture (extended version) - Jan Kraus

● Working with file:// protocol is unreliable. ● Use web server

○ Apache2○ PHP○ Node.js○ Ruby/Python

● Vagrant● MAMP / WAMP

○ I don’t recommend

Serving files locally

Page 23: HTML, CSS & Javascript Architecture (extended version) - Jan Kraus

Apache2

● Most popular server● Already available in Mac OS X & Ubuntu

○ Need little bit of tweaking, config breaks after update

● I guess also possible on Windows…● Need to setup virtual hosts if you have multiple sites

○ I prefer to do this anyway

Page 24: HTML, CSS & Javascript Architecture (extended version) - Jan Kraus

● Easy to use● Available from PHP 5.4

○ Available in OS X (5.6), Easy to install on Ubuntu (5.5)■ apt-get install php5

○ I guess also possible on windows…

● php -S localhost:8080

PHP built-in server

Page 25: HTML, CSS & Javascript Architecture (extended version) - Jan Kraus

● Useful when you’re building Webapp / SPA● Just one gulp plugin

○ npm install --save-dev gulp-connect

● Not so easy for dynamic templates

gulp.task('server', function() {

connect.server();

});

Node.js / gulp-connect

Page 26: HTML, CSS & Javascript Architecture (extended version) - Jan Kraus

● Full OS using virtualization● Every developer have the same environment● Powerful configuration

○ You can keep that in git○ Requires some knowledge

● Useful for framework setup with lots of dependencies● Slow and problematic on windows

Vagrant

Page 27: HTML, CSS & Javascript Architecture (extended version) - Jan Kraus

Automatization

● Compile & minify SASS● Concatenate / minify javascript files● Optimize images● Generate sprites● Code linting● Autoreload● Deployments

Page 28: HTML, CSS & Javascript Architecture (extended version) - Jan Kraus

Task runners

There are many ways to do it

● Grunt● Gulp● node.js● Shell

Page 29: HTML, CSS & Javascript Architecture (extended version) - Jan Kraus

Grunt

The JavaScript Task Runner

● Configuration…● Lots of plugins ● Operates on files● But…

○ Seems like not updated lately○ Community shifted to gulp

Page 30: HTML, CSS & Javascript Architecture (extended version) - Jan Kraus

● Install grunt CLI○ npm install -g grunt-cli

● Install local plugins○ npm install grunt-contrib-uglify --save-dev

● Configure○ Gruntfile.js

● Run: ○ grunt

Grunt

Page 31: HTML, CSS & Javascript Architecture (extended version) - Jan Kraus

Grunt - package.json

{

"name": "my-project-name",

"version": "0.1.0",

"devDependencies": {

"grunt": "~0.4.5",

"grunt-contrib-uglify": "~0.5.0"

}

}

Page 32: HTML, CSS & Javascript Architecture (extended version) - Jan Kraus

module.exports = function(grunt) {

grunt.initConfig({

uglify: {

build: {

files: [{

cwd: 'src/js',

src: '**/*.js',

dest: 'build/bundle.min.js'

}]

}

}

});

grunt.loadNpmTasks('grunt-contrib-uglify');

grunt.registerTask('default', ['uglify']);

};

Grunt - Gruntfile.js

Page 33: HTML, CSS & Javascript Architecture (extended version) - Jan Kraus

Automate and enhance your workflow

● Gulp is the new grunt● Active community● Simple configuration● Organized around streams● Faster & less config

gulp.js

Page 34: HTML, CSS & Javascript Architecture (extended version) - Jan Kraus

gulp.js

● Install gulp○ npm install --global gulp○ npm install --save-dev gulp

● Install plugins○ npm install --save-dev gulp-uglify

● Configure○ gulpfile.js

● Run:○ gulp

Page 35: HTML, CSS & Javascript Architecture (extended version) - Jan Kraus

gulp - gulpfile.js

var gulp = require('gulp');

var uglify = require('gulp-uglify');

gulp.task('uglify', function() {

return gulp.src(src/**/*.js')

.pipe(uglify())

.pipe(gulp.dest('dist'));

});

gulp.task('default', ['uglify']);

Page 36: HTML, CSS & Javascript Architecture (extended version) - Jan Kraus

npm & node.js packages

npm is the package manager for node.js

● pure node.js packages● simple setup, without much of configuration● easy to maintain

Page 37: HTML, CSS & Javascript Architecture (extended version) - Jan Kraus

npm

● Install package○ npm install jshint --save-dev

● Configure○ package.json

● Run○ npm run script name

Page 38: HTML, CSS & Javascript Architecture (extended version) - Jan Kraus

npm - package.json

"devDependencies": {

"jshint": "latest",

},

"scripts": {

"lint": "jshint **.js"

}

Page 39: HTML, CSS & Javascript Architecture (extended version) - Jan Kraus

A package manager for the web

● manage & download external dependencies● fetch and update frontend libraries

Bower

Page 40: HTML, CSS & Javascript Architecture (extended version) - Jan Kraus

● Install bower○ npm install -g bower

● Configure○ .bowerrc

■ {"directory": "assets/vendors/"}

● Install○ bower install jquery --save-dev

Bower

Page 41: HTML, CSS & Javascript Architecture (extended version) - Jan Kraus

{

"name": "Sample Project",

"devDependencies": {

"jquery": "~2.1.4"

}

}

Bower - bower.json

Page 42: HTML, CSS & Javascript Architecture (extended version) - Jan Kraus

Semantic versioning

Semantic versioning: MAJOR.MINOR.PATCH

● Patch releases: 1.0 or 1.0.x or ~1.0.4● Minor releases: 1 or 1.x or ^1.0.4● Major releases: * or x

Page 43: HTML, CSS & Javascript Architecture (extended version) - Jan Kraus

Getting started

Take something as your starting point:

● Web Starter Kit from Google● HTML5 Boilerplate● Bootstrap● yeoman generator

Page 44: HTML, CSS & Javascript Architecture (extended version) - Jan Kraus

Web Starter Kit is an easy way to start a new project.

● build process, ● boilerplate HTML ● styles (material design)

Web Starter Kit from Google

Page 45: HTML, CSS & Javascript Architecture (extended version) - Jan Kraus

HTML5 Boilerplate

The web’s most popular front-end template

● HTML Page Structure● Normalize.css● Modernizr.js● jQuery from CDN with local fallback

Page 46: HTML, CSS & Javascript Architecture (extended version) - Jan Kraus

Bootstrap from Twitter

Bootstrap is the most popular HTML, CSS, and JS framework for developing responsive, mobile first projects on the web.

● Not really a boilerplate● But you can use basic template● http://getbootstrap.com/getting-started/#template

Page 47: HTML, CSS & Javascript Architecture (extended version) - Jan Kraus

● Start using git if you haven’t already started○ Github - free for open source projects○ Bitbucket - unlimited private repositories, limited users○ Gitlab - self hosted github UI clone

Git

Page 48: HTML, CSS & Javascript Architecture (extended version) - Jan Kraus

Git - commits convention

[FEATURE] Implements lazy loading for products carousel (max 70 chars)

Adds JS module to loads products for carousel using AJAX triggered after document

ready. Implementation is using sttic JSON as example.

- JS module to load products

- CSS for loading animation

- Example of JSON for products

Ref: JIRA-1392

Page 49: HTML, CSS & Javascript Architecture (extended version) - Jan Kraus

● Basic○ only dev / master

● Feature branches○ use pull / merge requests for code review

● Gitflow○ when working on multiple releases & feature branches

Git - Branching model

Page 50: HTML, CSS & Javascript Architecture (extended version) - Jan Kraus

● git status○ read what’s there ;-)

● git reset○ git reset○ git reset head --hard○ git reset origin/master --force

● git revert○ git revert commit-sha○ creates new commit

Git - Command line

Page 51: HTML, CSS & Javascript Architecture (extended version) - Jan Kraus

● git cherry-pick○ git cherry-pick commit-sha○ creates new commit

● git rebase○ git rebase -i head~2○ is rewriting history

● git merge○ git merge your-branch-name○ resolve conflicts correctly

Git - Command line

Page 52: HTML, CSS & Javascript Architecture (extended version) - Jan Kraus

● git pull○ git fetch origin + git merge○ git pull --rebase

■ create cleaner history

● git stash○ git stash○ git stash pop

● git log○ git lg ○ git lg | grep JIRA-1234

Git - Command line

Page 53: HTML, CSS & Javascript Architecture (extended version) - Jan Kraus

● Libs○ jQuery○ Bootstrap○ Modernizr

● Frameworks○ Backbone○ Angular, Angular2○ Ember○ React

Framework & tools

Page 54: HTML, CSS & Javascript Architecture (extended version) - Jan Kraus

jQuery

● Site enhancements○ sliders○ galleries○ AJAX○ not much business logic

● DOM manipulation● Simple custom event system● Form validation

○ parsley.js

Page 55: HTML, CSS & Javascript Architecture (extended version) - Jan Kraus

Bootstrap

● UI library for the web● SCSS / Less components

○ Include only what you need with sass imports○ You can use SASS @extend

● Same for JS○ you can include only what you need

● Useful○ grid○ forms○ modal

Page 56: HTML, CSS & Javascript Architecture (extended version) - Jan Kraus

Modernizr

● Feature detection for browsers○ append CSS classes to html○ Modernizr JS object for testing properties

● Generate custom build● Does not have to be included in the head

Page 57: HTML, CSS & Javascript Architecture (extended version) - Jan Kraus

Backbone.js

● Simple structure for web application○ Models, Collections, Views, Routers○ Less abstraction○ Simple, still popula

● http://addyosmani.github.io/backbone-fundamentals/

Page 58: HTML, CSS & Javascript Architecture (extended version) - Jan Kraus

Angular

● The “enterprise” frameworks● Most popular kinda MVC framework● Easy 2 way binding● Performance issues● Angular 2 on the way

Page 59: HTML, CSS & Javascript Architecture (extended version) - Jan Kraus

React

● Library from Facebook● High performance

○ Virtual DOM

● Organized around components & state

Page 60: HTML, CSS & Javascript Architecture (extended version) - Jan Kraus

Useful libraries

● Moment.js● History.js● Respond.js

○ not really usefull

● Typeahead● Parsley.js

Page 61: HTML, CSS & Javascript Architecture (extended version) - Jan Kraus

RWD - Responsive web design

● Mobile first approach● Stop thinking in pixels

○ Multiple devices, screens, widths...

● Progressive enhancement / graceful degradation● SVG & retina images● Build your site with performance in mind● Read often:

○ http://www.smashingmagazine.com/○ https://css-tricks.com/

Page 62: HTML, CSS & Javascript Architecture (extended version) - Jan Kraus

Modular CSS

● Reusable components● Naming convention for CSS classes

○ SMACSS○ BEM○ OOCSS

Page 63: HTML, CSS & Javascript Architecture (extended version) - Jan Kraus

Scalable & Modular Architecture for CSS

● Simple naming conventions● Architecture & patterns for organizing rules● Free book:

○ https://smacss.com/book/

SMACSS

Page 64: HTML, CSS & Javascript Architecture (extended version) - Jan Kraus

-theme.scss

- theme/_base.scss

- theme/base/_reset.scss

- theme/base/_headings.scss

- theme/_layout.scss

- theme/layout/_masthead.scss

- theme/layout/_main.scss

- theme/layout/_footer.scss

- theme/_modules.scss

- theme/modules/_search.scss

- theme/modules/_gallery.scss

- theme/_state.scss

- theme/state/_mediaqueries.scss

SMACSS - Organization

Page 65: HTML, CSS & Javascript Architecture (extended version) - Jan Kraus

BEM

BEM – Block Element Modifier is a methodology, that helps you to achieve reusable components and code sharing in the front-end

● Naming conventions● Independent modular blocks● Flexible and allows for customization

Page 66: HTML, CSS & Javascript Architecture (extended version) - Jan Kraus

BEM - Example

.block {}

.block__element {}

.block--modifier {}

// example of search for

.site-search {} /* Block */

.site-search__field {} /* Element */

.site-search--full {} /* Modifier */

Page 68: HTML, CSS & Javascript Architecture (extended version) - Jan Kraus

Learn more

● http://www.smashingmagazine.com/● https://css-tricks.com/● JS News Facebook group: https://www.facebook.

com/groups/217169631654737/● https://www.reddit.com/r/webdev● Newsletters:

○ http://html5weekly.com/○ http://css-weekly.com/○ http://javascriptweekly.com/

Page 69: HTML, CSS & Javascript Architecture (extended version) - Jan Kraus

Thank you!