background preloader

24 JavaScript Best Practices for Beginners

24 JavaScript Best Practices for Beginners
As a follow-up to "30 HTML and CSS Best Practices", this week, we'll review JavaScript! Once you've reviewed the list, be sure to let us know what little tips you've come across! JavaScript utilizes two different kinds of equality operators: === | !== and == | != It is considered best practice to always use the former set when comparing. "If two operands are of the same type and value, then === produces true and ! However, when working with == and ! For those unfamiliar, the "eval" function gives us access to JavaScript's compiler. Not only will this decrease your script's performance substantially, but it also poses a huge security risk because it grants far too much power to the passed in text. Technically, you can get away with omitting most curly braces and semi-colons. However, consider this: One might think that the code above would be equivalent to: Unfortunately, he'd be wrong. As you'll notice, the indentation mimics the functionality of the curly brace. Consider the following code: Related:  HTML / CSS / JSJavascriptBonnes pratiques

Getting started with Grunt and Sass - Ryan Christiani - Front-End Developer - Ryan Christiani – Front-End Developer There are a lot of new tools out there to help speed up and streamline your workflow as a developer, and to be honest they can seem a bit daunting to get into. Two new tools I have started using this year were Grunt and Sass. Grunt is a commandline JavaScript Task Runner, and Sass is a Css preprocessor that lets you write more powerful css, with the use of variables, mixins/functions and nesting! Lets take a look at getting started using Grunt to compile our Sass. If you are new to the working in the command line, check my quick overview of some of the basic commands to help get you started. Dependencies To get started you will need to install a few things. If you are using windows you will have to install Ruby, the Ruby Installer is pretty painless, be sure to check the “Add Ruby executable to your PATH” option. You will also need to grab and install NodeJs, this is pretty straight forward. Grunt Getting started with grunt is pretty simple. npm install -g grunt-cli Example: Sass

Lazy Load Plugin for jQuery Lazy Load is delays loading of images in long web pages. Images outside of viewport are not loaded until user scrolls to them. This is opposite of image preloading. Using Lazy Load on long web pages will make the page load faster. In some cases it can also help to reduce server load. Plugin is inspired by YUI ImageLoader Utility by Matt Mlinac. For those in hurry there are several demo pages: basic options, with fadein effect, noscript fallback, horizontal scrolling, horizontal scrolling inside container, vertical scrolling inside container, page with gazillion images, load images using timeout and load images using AJAX(H). When checking the demos clear browser cache between each request. How to Use? Lazy Load depends on jQuery. You must alter your image tags. <img class="lazy" data-original="img/example.jpg" width="640" height="480"> $(function() { $("img.lazy").lazyload(); }); This causes all images of class lazy to be lazy loaded. PRO TIP! Setting Threshold Event to Trigger Loading

Avinash Meetoo: Blog » A regular expression to check for prime n Regular expressions are extremely powerful. This is something I read at least once or twice every day while reading articles and blogs on the Web. While browsing today, I found this page which thoroughly describes the use of the regular expression /^1?$|^(11+?)\1+$/ in Perl to check if a number is prime or not!!! To be frank, I was skeptical. Avinash@noulakaz:~$ irb irb(main):001:0> def is_prime(n) irb(main):002:1> ("1" * n) ! Great! Is 7 prime? To know this, the function first generates “1111111″ (from “1″ * 7) and tries to see if that string does not match /^1? Notice that the regular expression has two parts (separated with the vertical bar |). The first part is /^1? The second part is where the magic occurs… /^(11+?) Let’s proceed slowly… (11+?) It matches with “1″ followed by one or more ones minimally. \1+ then matches with whatever has been matched above (“11″ initially) repeated one or more times. As for odd numbers (in our case 7), the (11+?) “1″ * 9 = “111111111″. (11+?)

Bonnes pratiques javascript Ce préfixe javascript: est encore une relique honteuse d'une autre époque. Il ne doit jamais apparaitre. Il est inutile de l'utiliser sachant que le code javascript n'a rien à faire dans un attribut href d'une balise <a> . Dans l'attribut href d'un lien doit figurer une URI valide qui pointe effectivement sur une ressource, dans ce cas javascript: est traité comme un protocole ! Protocole qui n'existe pas ; le lien est alors invalide et inutile. La solution est simple. <a href="/supprimer/id" onclick="return confirm('Supprimer cet objet ?') Maintenant pour les actions ne possédant pas d'url — le démarrage d'un compte à rebours, le changement de couleur d'un élément, cacher un élément (les <secret> et autre) — la balise consacrée est nommée <button> et possède un attribut type qui peut prendre les valeurs button il n'y a pas d'action par défaut, le bouton ne « fait rien »,submit c'est la valeur par défaut. L'utilisation est simple : <button type="button" onclick="cacher();">Cachez moi !

Benchmark.js Lassés de Bootstrap ? Découvrez inuit.css ! | @nicoespeon inuit.css est un framework CSS extensible, construit sur un ensemble de bonnes pratiques CSS et qui n'impose pas de design prédéfini. inuit.css est-il fait pour vous ? Pour faire simple, voici les cas de figure dans lesquels ce framework peut vous intéresser : Vous avez besoin de mettre en place rapidement une architecture CSS décenteVous découvrez/connaissez les avantages du code Orienté Objet et appréciez son adaptabilité et sa réusabilitéVous devez implémenter un certain design qui ne colle pas forcément aux éléments “par défaut” des autres frameworksVous aimez le concept de framework mais, développeur dans l’âme, aimez avoir la main-mise sur le code Et voici clairement le cas de figure où vous pouvez passer votre chemin (sauf si vous êtes curieux) : Vous cherchez un framework CSS qui prenne en charge le design des éléments En ce qui me concerne, je suis un assez grand utilisateur de Bootstrap. Je suis donc tombé sur inuit.css, à peu près par hasard. Philosophie Installation

Introduction to JavaScript Source Maps Have you ever found yourself wishing you could keep your client-side code readable and more importantly debuggable even after you've combined and minified it, without impacting performance? Well now you can through the magic of source maps. Basically it's a way to map a combined/minified file back to an unbuilt state. Demo: Get original location The above demo allows you to right click anywhere in the textarea containing the generated source. Real world Before you view the following real world implementation of Source Maps make sure you've enabled the source maps feature in either Chrome Canary or WebKit nightly by clicking the settings cog in the dev tools panel and checking the "Enable source maps" option. Firefox 23+ has source maps enabled by default in the built in dev tools. So... Demo: View scripts panel (with source maps) on Why should I care about source maps? Demo: Write ES6, debug it, view source mapping in action How does the source map work? Potential XSSI issues

HTTP/1.1: Status Code Definitions Each Status-Code is described below, including a description of which method(s) it can follow and any metainformation required in the response. 10.1 Informational 1xx This class of status code indicates a provisional response, consisting only of the Status-Line and optional headers, and is terminated by an empty line. There are no required headers for this class of status code. Since HTTP/1.0 did not define any 1xx status codes, servers MUST NOT send a 1xx response to an HTTP/1.0 client except under experimental conditions. A client MUST be prepared to accept one or more 1xx status responses prior to a regular response, even if the client does not expect a 100 (Continue) status message. Proxies MUST forward 1xx responses, unless the connection between the proxy and its client has been closed, or unless the proxy itself requested the generation of the 1xx response. 10.1.1 100 Continue The client SHOULD continue with its request. 10.1.2 101 Switching Protocols 10.2 Successful 2xx - Date

JavaScript Best Practices Essential JavaScript Design Patterns For Beginners Design patterns are reusable solutions to commonly occurring problems in software design. They are both exciting and a fascinating topic to explore in any programming language. One reason for this is that they help us build upon the combined experience of many developers that came before us and ensure we structure our code in an optimized way, meeting the needs of problems we're attempting to solve. Design patterns also provide us a common vocabulary to describe solutions. In this book we will explore applying both classical and modern design patterns to the JavaScript programming language. Target Audience This book is targeted at professional developers wishing to improve their knowledge of design patterns and how they can be applied to the JavaScript programming language. Some of the concepts covered (closures, prototypal inheritance) will assume a level of basic prior knowledge and understanding. Acknowledgments Credits Reading

HTML5 Web Storage Light Table - a new IDE concept You can now try Light Table out via the Light Table Playground! Light Table's kickstarter has wrapped up! Despite the dramatic shift toward simplification in software interfaces, the world of development tools continues to shrink our workspace with feature after feature in every release. Even with all of these things at our disposal, we're stuck in a world of files and forced organization - why are we still looking all over the place for the things we need when we're coding? Why is everything just static text? Bret Victor hinted at the idea that we can do much better than we are now - we can provide instant feedback, we can show you how your changes affect a system. We can do better, and to that end, let me introduce you to Light Table is based on a very simple idea: we need a real work surface to code on, not just an editor and a project explorer. Light table is based on a few guiding principles: Let's take a look at how these things manifest themselves in Light Table. Docs everywhere

Related:  Best Practice