Get found on the web

Quality Web Design for Small
to Medium Businesses in New Hampshire

Useful Coding Tools and JavaScript Libraries For Web Developers

Posted on by Portsmouth Media in Blog Comments Off

An article I was reading about css3





 



 


Everyone who is a regular Smashing Magazine reader will know that we have a traditional habit of regularly researching the latest resources, tools and services out there on the Web, as productivity is a crucial asset of professional Web designers and developers. We could, and should, all integrate workflow optimization into our working practices.

Perhaps we should warn you upfront for the long compilation, but what can we say — there are so many excellent tools out there which deserve attention of the community, yet unfortunately remain obscure way too often. We love all the designers and developers out there for releasing and producing useful, valuable resources for all of us to use! We, for one, surely sincerely appreciate it in the name of the Web design community. Whether you like it or not, here are some of the most useful coding and workflow tools released recently.

Feel free to comment to this post and let us know how exactly you use these tools in your workflow and also share other tools you’ve found with others who may also find them useful and still haven’t run across them. Please do avoid link dropping and share your insights and your experience instead.

Useful Coding and Workflow Tools

Stripe: Easy Credit-Card Processing For Online Stores
A website owner has many options for accepting credit card payments. Most of those options have a verification process that is quite slow; some have APIs and interfaces that are more or less robust than others; and some solutions are much easier to use than others. With Stripe, you can forget the tedious experience of the PayPal API and other mysterious programming environments. Unfortunately, Stripe is currently available only in the US.

Stripe: Easy Credit-Card Processing For Online Stores

The Web Developer’s Wonderland
Web development comes with truly enjoyable, creative tasks and some mundane, boring ones. Probably the most frustrating task is having to reload the browser page during development or debugging every time you make a change to the page. Livereload is a desktop app that monitors changes in your file system. As soon as you save a file, the file is preprocessed as needed, and the browser is refreshed. Also, every time you change a CSS file or image, the browser is updated instantly without you having to reload the page. The tool supports CoffeeScript, SASS/SCSS, LESS, Stylus, HAML and Jade, and it ships with all of them included. Currently available only for Mac.

The Web Developer’s Wonderland

Ender: The End Of Monolithic JavaScript Libraries
Ender allows you to search, install, manage and compile front-end JavaScript packages and their dependencies. Essentially, it’s a command-line tool that allows you to combine and mix all of the popular and small JavaScript libraries out there to create your own personal development library. If one library you use goes bad or is abandoned, Ender will help you quickly replace it with another. And if you need a particular version of a package, the tool can help you out as well. The release page contains detailed documentation, a user guide and some video tutorials. No more wasted bandwidth!

Ender: the end of monolithic JS libraries

Open-Source Exchange Rates and Currency Conversion
So, you’d like your customers to be able to purchase your products in various currencies, but how exactly do you build this functionality into your product? Finding a free and reliable API for developers to access the rates data is darn hard. Joss Crowcroft has created an Open Source Exchange Rates API, which provides up-to-date, flexible and portable currency-conversion data that can be used in any application, framework or language (not just JavaScript). It has no access fees, no rate limits, no nasty XML: just free, hourly updated exchange rates in JSON. Even better: Joss has also built money.js, a JavaScript currency conversion library that can be easily integrated in any website. A demo playground and detailed documentation are provided on the website, and the source code is available on GitHub.

Open-Source Exchange Rates and Currency Conversion

Easier Number and Currency Formatting
This simple, tiny JavaScript library will solve your currency and numbers-related formatting hassles, and it even includes optional Excel-style column rendering to line up symbols and decimals. It will make all of your numbers and currencies look much more uniform and professional than they would if left to many content creators.

Easier Number and Currency Formatting

Tilt Firefox Extension: DOM Inspection In 3-D
How much time do you spend traversing the DOM in Firebug, exploring the relationships between nodes, analyzing the structure of code and trying to manipulate it with nasty (or not so nasty) JavaScript? Well, perhaps you’d like to try a different approach to DOM inspection for a change. Mozilla’s new tool, Tilt Firefox Extension lets you visualize the DOM tree of any Web page in 3-D. Because the DOM is essentially a tree-like representation of a document, the developers of the tool have decided to layer nodes based on the nesting in a tree, creating stacks of elements, each with a corresponding depth, and textured according to the Web page being rendered.

Tilt Firefox Extension: DOM Inspection in 3D

Mou – Markdown editor for web developers, on Mac OS X
When current available Markdown editors are almost all for general writers, Mou is different: It’s for web developers. Syntax highlighting, live preview, fullscreen mode, auto save, powerful actions, auto pair, incremental search, custom themes, HTML export, enhanced CJK characters support. It’s exactly the app you want.

Mou - Markdown editor for web developers, on Mac OS X

Creating Buzz With Launch Effect
The one-page theme lets visitors sign up using their email. Upon signing up, the page generates a special URL for them to share with their friends, so that you can track your most active promoters and reward them for spreading the word. What more do you need from a pre-launch page? This is a good tool to bookmark for your next creative breakthrough or start-up idea.

Making a Buzz With the Launch Effect

A Better Responsive Grid
The Golden Grid System uses the concept of “folding” grid columns into one another, based on the browser’s size. So, a 16-column grid that works great in desktop browsers would fold down to an 8-column grid for tablets, and a 4-column grid for mobile devices. It can handle screen sizes ranging anywhere from 240 pixels wide all the way up to 2560 pixels. The columns themselves are not the only things that are elastic either; while the column’s widths are based on screen size, the gutter widths adjust based on the page’s font size (specified in ems). The Golden Grid System comes with other features that make it perfectly suited to modern responsive Web design.

A Better Responsive Grid

The Semantic Grid System
CSS grid frameworks can make your life easier, but they’re not without their faults. Fortunately for us, modern techniques offer a new approach to constructing page layouts. But before getting to the solution, we must first understand the three seemingly insurmountable flaws currently affecting CSS grids.

The Semantic Grid System

Bootstrap Kick-Start Development Toolkit
Bootstrap is a toolkit that includes the base CSS and HTML for typography, tables, grids, navigation, error messages, modal boxes, buttons and forms. It’s built with the LESS framework. It comes with a standard 940-pixel grid (i.e. 960.gs without the side margins), or you can create your own. Bootstrap allows you to create fixed or fluid layouts, and it comes with many elements that can be used as is or restyled to fit your website. Of course, the toolkit is free to use.

Kickstart Your Website and App Development

Colour Bookmark
Drag the Colour Bookmark link to your toolbar to find out the colour palette of the website you’re currently on. Then simply: copy, paste and use the colours you choose.

Colour Bookmark

Leaflet: Open-Source Interactive Maps with JavaScript
The library offers a variety of map layers, including tiles, markers, pop-ups, image overlays and GeoJSON. It supports panning on both mobile and desktop browsers, double-tap zoom on mobile browsers (plus multi-touch zoom on iOS) and more. On iOS, hardware acceleration is enabled, and Leaflet has a modular structure that lets you reduce the size of the library to make it even faster. The project is open source and available for further development and forking on GitHub.

Leaflet

Weinre
weinre is a Web Inspector Remote that is essentially a debugger for web pages, like FireBug (for FireFox) and Web Inspector (for WebKit-based browsers), except it’s designed to work remotely, and in particular, to allow you debug web pages on a mobile device such as a phone.

Weinre

Aardwolf: Remote JavaScript Debugger
Mobile browsers are becoming more powerful day-by-day and you can do almost everything you do on your desktop browser. One of the major concerns for the developers is the lack of developer tools. The reasons are quite obvious — real estate needed to show the debugger, non-developer friendly environment. The solution to this problem is remote debugging. You can use JSConsole for this purpose but when it comes to JavaScript debugging, Aardwolf is a better choice. Aardwolf is a JavaScript debugger for iPhone / Android / WindowsPhone 7 / BlackBerry OS 6+. (via Varun Kumar)

Varun's ScratchPad: JavaScript Remote Debugging

IE Vms
Microsoft provides virtual machine disk images to facilitate website testing in multiple versions of IE, regardless of the host operating system. But setting these virtual machines up without Microsoft’s VirtualPC can be extremely difficult. The ievms scripts aim to facilitate that process using VirtualBox on Linux or OS X. With a single command, you can have IE7, IE8 and IE9 running in separate virtual machines.

IE Vms

WhatFont
The tool allows you to easily get CSS typography details about the text you are hovering on.

WhatFont

WordPress TextMate Bundle
The WordPress TextMate Bundle is a TextMate bundle built with the sole purpose of reducing the amount of time spent digging around the WordPress core to look up the little things that we work with every day. The plugin features auto-completion of WordPress functions, snippets for common sections of code, and templates for WordPress components. We even snuck in function completion for the Carrington template framework functions. We’re always making improvements as we find more that we want covered by the plugin (merged from WordPress MU with the WordPress 3.0 code base consolidation).

WordPress TextMate Bundle

cubic-bezier previewer
No matter how much you see someone changing the parameters, if you don’t picture it in a 2D plane, it’s very hard to understand how bouncing animation with cubic-bezier works. Lea Verou searched for a tool could use to show how bezier curves are formed. She found plenty, but all of them restricted the the coordinates to the 0-1 range. Lea then proceded to create her own cubic_bezier() curves generator.

cubic-bezier.com

Patternizer – Stripe Pattern Generator Tool
With Patternizer, it’s easy to make something amazing in just a few minutes. It takes all the work out of creating complicated patterns, letting you focus on creativity and play. Patterns can be saved and shared with anyone, allowing for collaboration and remixing. And you can access them from any device worldwide.

Patternizer - Stripe Pattern Generator Tool

Chainvas
A tiny, modular library that can add chaining to any API that isn’t naturally chainable, like the Canvas API, the DOM and more.

Chainvas

Comparison Table Generator
This generator allows you to create beautiful HTML/CSS comparison tables on the fly.

Compare Ninja Table Generator

DropKick.js
A custom drop-down jQuery plugin which degrades gracefully. If the user has JavaScript disabled, the drop-down will display normally using regular <select> elements. It works on IE7+.

DropKick.js

-prefixfree
-prefix-free lets you use only unprefixed CSS properties everywhere. It works behind the scenes, adding the current browser’s prefix to any CSS code, only when it’s needed.

Prefixfree

{less}
An automated folder scanning/parsing tool for LESS. Once you add your project folders to the application, it will automatically start monitoring the less files inside these folders for changes. After you have saved the less file, the application will automatically parse your less file into a regular CSS file. Also, see: SimpLESS, an app for Mac, Linux and PC to compile *.less files into valid CSS.

SimpLESS

Recurly.js
This tool allows you to easily embed a PCI compliant order form within your website. The library performs in-line validation, real-time total calculations, and gracefully handles errors. Your customer stays on your website while their billing information is securely sent to Recurly for approval. Because the cardholder data is sent directly to Recurly, your PCI compliance scope is dramatically reduced.

Recurly.js

Responsive Overlay Grid for In-Browser Development
The Heads-Up Grid is a recently released grid overlay for in-browser development. It works with fixed-width designs but also works great with responsive grids. Just specify the page units, column units, page width, number of columns, column width, gutter width, top margin and row height, and then paste the Heads-Up Grid code into the head element of your website to generate the grid overlay.

Responsive-Compatible Overlay Grid for In-Browser Development

Has.js
The library is similar to Modernizr, but instead of testing for HTML5/CSS3 features, it tests for JavaScript features such as: ES5 array, string, and object featuresNative JSON supportNative console supportActiveXNative XHRSome DOM and event features.

grumble.js
This library allows you to create tooltips that can be rotated around a given element at any angle. Any distance can be specified. Any CSS style can be applied. There’s auto-magic size adjustment for use with localised text. FX queues for animating multiple grumbles. And it works in IE6+, and all modern browsers.

testling: Automated Cross-Browser JavaScript Testing
An automated cross-browser JavaScript testing platform for your quality assurance.

Instant WordPress
A standalone, portable WordPress development environment for Windows that can run from USB.

CSS Stress Testing and Profiling
A bookmarklet for stress testing the CSS on any given webpage. It indexes all the elements and their classes, and then — class by class — it removes one, and times how long it takes to scroll the page. Selectors that save a considerable amount of time when removed indicate problem areas.

Needle: Automated Tests for Your CSS
This tool checks that CSS renders correctly by taking screenshots of portions of a website and comparing them against known good screenshots. It also provides tools for testing calculated CSS values and the position of HTML elements.

Last Click

Cutting-Edge Web Typography Experiments
The website is essentially an ongoing collection of experiments and writings on Web typography and the possibilities of cutting-edge standards-based Web design. Christopher is pushing the boundaries of what is both possible and practical in Web standards in a way that is compelling and exciting to the visually minded creative.

Cutting-Edge Web Typography Experiments

Font-Bot
It is time for your favorite font to stand its ground. The idea of this project is to build robots out of typeface glyphs, showcase them and hope others put together an opponent. Participating is not hard, the rules are clear: all Robots must be built of type alone (A-Z). You may reflect and rotate the letters. Keep it civil. May the best bot win. Let’s see if your type design has what it takes to defend its corner. Fight!

Font-Bot

Lights
“Lights” is an interactive music experience which is created with CSS, JavaScript and HTML5. This is why we love the Web.

Lights

Stay Tuned!

More posts with useful tools and techniques are coming very soon here, on Smashing Magazine. If you want to be among the first to be informed about the new tools, resources and techniques, please

You won’t regret it. Thank you.

Thank you to the Smashing Editorial team, especially Christiane Rosenberger, Iris Ljesnjanin and Luca Degasperi for their help in preparing and editing the post.


© Vitaly Friedman for Smashing Magazine, 2011.

Smashing Magazine Feed


Lessons From A Review Of JavaScript Code

Posted on by Portsmouth Media in Blog Comments Off

An article I was reading about css3





 



 


Before we start, I’d like to pose a question: when was the last time you asked someone to review your code? Reviewing code is possibly the single best technique to improve the overall quality of your solutions, and if you’re not actively taking advantage of it, then you’re missing out on identifying bugs and hearing suggestions that could make your code better.

None of us write 100% bug-free code all of the time, so don’t feel there’s a stigma attached to seeking help. Some of the most experienced developers in our industry, from framework authors to browser developers, regularly request reviews of their code from others; asking whether something could be tweaked should in no way be considered embarrassing. Reviews are a technique like any other and should be used where possible.

Today we’ll look at where to get your code reviewed, how to structure your requests, and what reviewers look for. I was recently asked to review some code for a new JavaScript application, and thought I’d like to share some of my feedback, because it covers some JavaScript fundamentals that are always useful to bear in mind.

Introduction

Reviewing code goes hand in hand with maintaining strong coding standards. That said, standards don’t usually prevent logical errors or misunderstandings about the quirks of a programming language, whether it’s JavaScript, Ruby, Objective-C or something else. Even the most experienced developers can make these kinds of mistakes, and reviewing code can greatly assist with catching them.

The first reaction most of us have to criticism is to defend ourselves (or our code), and perhaps lash back. While criticism can be slightly demoralizing, think of it as a learning experience that spurs us to do better and to improve ourselves; because in many cases, once we’ve calmed down, it actually does.

Also remember that no one is obliged to provide feedback on your work, and if the comments are indeed constructive, then be grateful for the time spent offering the input.

Reviews enable us to build on the experience of others and to benefit from a second pair of eyes. And at the end of the day, they are an opportunity for us to write better code. Whether we take advantage of them is entirely our choice.

Where Can I Get My Code Reviewed?

Often the most challenging part is actually finding an experienced developer who you trust to do the review. Below are some places where you can request others to review your code (sometimes in other languages, too).

  • JSMentors
    JSMentors is a mailing list that discusses everything to do with JavaScript (including Harmony), and a number of experienced developers are on its review panel (including JD Dalton, Angus Croll and Nicholas Zakas). These mentors might not always be readily available, but they do their best to provide useful, constructive feedback on code that’s been submitted. If you’re looking for assistance with a specific JavaScript framework beyond vanilla JavaScript, the majority of frameworks and libraries have mailing lists or forums that you can post to and that might provide a similar level of assistance.
  • freenode IRC
    Many chat rooms here are dedicated both to discussing the JavaScript language and to requests for help or review. The most popular rooms are obviously named, and #javascript is particularly useful for generic JavaScript requests, while channels such as #jquery and #dojo are better for questions and requests related to particular libraries and frameworks.
  • Code Review (beta)
    You would be forgiven for confusing Code Review with StackOverflow, but it’s actually a very useful, broad-spectrum, subjective tool for getting peer review of code. While on StackOverflow you might ask the question “Why isn’t my code working?,” Code Review is more suited to questions like “Why is my code so ugly?” If you still have any doubt about what it offers, I strongly recommend checking out the FAQs.
  • Twitter
    This might sound odd, but at least half of the code that I submit for review is through social networks. Social networks work best, of course, if your code is open source, but trying them never hurts. The only thing I suggest is to ensure that the developers who you follow and interact with are experienced; a review by a developer with insufficient experience can sometimes be worse than no review at all, so be careful!
  • GitHub + reviewth.is
    We all know that GitHub provides an excellent architecture for reviewing code. It comes with commits, file and line comments, update notifications, an easy way to track forks of gits and repositories, and more. All that’s missing is a way to actually initiate reviews. A tool called reviewth.is attempts to rectify that by giving you a post-commit hook that helps to automate this process, so changes that get posted in the wild have a clear #reviewthis hash tag, and you can tag any users who you wish to review your updates. If many of your colleagues happen to develop in the same language as you do, this set-up can work well for code reviews sourced closer to home. One workflow that works well with this (if you’re working on a team or on a collaborative project) is to perform your own work in a topic branch in a repository and then send through pull requests on that branch. Reviewers would examine the changes and commits and could then make line-by-line and file-by-file comments. You (the developer) would then take this feedback and do a destructive rebase on that topic branch, re-push it, and allow the review cycle to repeat until merging them would be acceptable.

How Should I Structure My Review Requests?

The following are some guidelines (based on experience) on how to structure your requests for code reviews, to increase the chances of them being accepted. You can be more liberal with them if the reviewer is on your team; but if the reviewer is external, then these might save you some time:

  • Isolate what you would like to be reviewed; ensure that it can be easily run, forked and commented; be clear about where you think improvements could be made; and, above all, be patient.
  • Make it as easy as possible for the reviewer to look at, demo and change your code.
  • Don’t submit a ZIP file of your entire website or project; very few people have the time to go through all of this. The only situation in which this would be acceptable is if your code absolutely required local testing.
  • Instead, isolate and reduce what you would like to be reviewed on jsFiddle, on jsbin or in a GitHub gist. This will allow the reviewer to easily fork what you’ve provided and to show changes and comments on what can be improved. If you would prefer a “diff” between your work and any changes they’ve recommended, you might also be interested in PasteBin, which supports this.
  • Similarly, don’t just submit a link to a page and ask them to “View source” in order to see what can be improved. On websites with a lot of scripts, this task would be challenging and lowers the chances of a reviewer agreeing to help. No one wants to work to find what you want reviewed.
  • Clearly indicate where you personally feel the implementation could be improved. This will help the reviewer quickly home in on what you’re most interested in having reviewed and will save them time. Many reviewers will still look at other parts of the code you’ve submitted regardless, but at least help them prioritize.
  • Indicate what (if any) research you’ve done into techniques for improving the code. The reviewer might very well suggest the same resources, but if they’re aware that you already know of them, then they might offer alternative suggestions (which is what you want).
  • If English isn’t your first language, there’s no harm in saying so. When other developers inform me of this, I know whether to keep the language in my review technical or simple.
  • Be patient. Some reviews take several days to get back to me, and nothing’s wrong with that. Other developers are usually busy with other projects, and someone who agrees to schedule a look at your work is being kind. Be patient, don’t spam them with reminders, and be understanding if they get delayed. Doing this sometimes pay off, because the reviewer can provide even more detailed feedback when they have more time.

What Should Code Reviews Provide?

Jonathan Betz, a former developer at Google, once said that a code review should ideally address six things:

  1. Correctness
    Does the code do everything it claims?
  2. Complexity
    Does it accomplish its goals in a straightforward way?
  3. Consistency
    Does it achieve its goals consistently?
  4. Maintainability
    Could the code be easily extended by another member of the team with a reasonable level of effort?
  5. Scalability
    Is the code written in such a way that it would work for both 100 users and 10,000? Is it optimized?
  6. Style
    Does the code adhere to a particular style guide (preferably one agreed upon by the team if the project is collaborative)?

While I agree with this list, expanding it into an action guide of what reviewers should practically aim to give developers would be useful. So, reviewers should do the following:

  • Provide clear comments, demonstrate knowledge, and communicate well.
  • Point out the shortfalls in an implementation (without being overly critical).
  • State why a particular approach isn’t recommended, and, if possible, refer to blog posts, gists, specifications, MDN pages and jsPerf tests to back up the statement.
  • Suggest alternative solutions, either in a separate runnable form or integrated in the code via a fork, so that the developer can clearly see what they did wrong.
  • Focus on solutions first, and style second. Suggestions on style can come later in the review, but address the fundamental problem as thoroughly as possible before paying attention to this.
  • Review beyond the scope of what was requested. This is entirely at the reviewer’s discretion, but if I notice issues with other aspects of a developer’s implementation, then I generally try to advise them on how those, too, might be improved. I’ve yet to receive a complaint about this, so I assume it’s not a bad thing.

Collaborative Code Reviews

Although a review by one developer can work well, an alternative approach is to bring more people into the process. This has a few distinct advantages, including reducing the load on individual reviewers and exposing more people to your implementation, which could potentially lead to more suggestions for improvements. It also allows a reviewer’s comments to be screened and corrected if they happen to make a mistake.

To assist the group, you may wish to employ a collaborative tool to allow all reviewers to simultaneously inspect and comment on your code. Luckily, a few decent ones out there are worth checking out:

  • Review Board
    This Web-based tool is available for free under the MIT license. It integrates with Git, CVS, Mercurial, Subversion and a number of other source-control systems. Review Board can be installed on any server running Apache or lighttpd and is free for personal and commercial use.
  • Crucible
    This tool by Australian software company Atlassian is also Web-based. It’s aimed at the enterprise and works best with distributed teams. Crucible facilitates both live review and live commenting and, like Review Board, integrates with a number of source-control tools, including Git and Subversion.
  • Rietveld
    Like the other two, Rietveld also supports collaborative review, but it was actually written by the creator of Python, Guido van Rossum. It is designed to run on Google’s cloud service and benefits from Guido’s experience writing Mondrian, the proprietary app that Google uses internally to review its code.
  • Others
    A number of other options for collaborative code review weren’t created for that purpose. These include CollabEdit (free and Web-based) and, my personal favorite, EtherPad (also free and Web-based).


(Image Source: joelogon)

Lessons From A JavaScript Code Review

On to the review.

A developer recently wrote in, asking me to review their code and provide some useful suggestions on how they might improve it. While I’m certainly not an expert on reviewing code (don’t let the above fool you), here are the problems and solutions that I proposed.

Problem 1

Problem: Functions and objects are passed as arguments to other functions without any type validation.

Feedback: Type validation is an essential step in ensuring that you’re working only with input of a desired type. Without sanitization checks in place, you run the risk of users passing in just about anything (a string, a date, an array, etc.), which could easily break your application if you haven’t developed it defensively. For functions, you should do the following at a minimum:

  1. Test to ensure that arguments being passed actually exist,
  2. Do a typeof check to prevent the app from executing input that is not a valid function at all.
if (callback && typeof callback === "function"){
    /* rest of your logic */
}else{
    /* not a valid function */
}

Unfortunately, a simple typeof check isn’t enough on its own. As Angus Croll points out in his post “Fixing the typeof operator,” you need to be aware of a number of issues with typeof checking if you’re using them for anything other than functions.

For example, typeof null returns object, which is technically incorrect. In fact, when typeof is applied to any object type that isn’t a function, it returns object, not distinguishing between Array, Date, RegEx or whatever else.

The solution is to use Object.prototype.toString to call the underlying internal property of JavaScript objects known as [[Class]], the class property of the object. Unfortunately, specialized built-in objects generally overwrite Object.prototype.toString, but you can force the generic toString function on them:

Object.prototype.toString.call([1,2,3]); //"[object Array]"

You might also find Angus’s function below useful as a more reliable alternative to typeof. Try calling betterTypeOf() against objects, arrays and other types to see what happens.

function betterTypeOf( input ){
    return Object.prototype.toString.call(input).match(/^\[object\s(.*)\]$/)[1];
}

Here, parseInt() is being blindly used to parse an integer value of user input, but no base is specified. This can cause issues.

In JavaScript: The Good Parts, Douglas Crockford refers to parseInt() as being dangerous. Although you probably know that passing it a string argument returns an integer, you should also ideally specify a base or radix as the second argument, otherwise it might return unexpected output. Take the following example:

parseInt('20');       // returns what you expect, however…
parseInt('020');      // returns 16
parseInt('000020');   // returns 16
parseInt('020', 10);  // returns 20 as we've specified the base to use

You’d be surprised by how many developers omit the second argument, but it happens quite regularly. Remember that your users (if permitted to freely enter numeric input) won’t necessarily follow standard number conventions (because they’re crazy!). I’ve seen 020, ,20, ;'20 and many other variations used, so do your best to parse as broad a range of inputs as possible. The following tricks to using parseInt() are occasionally better:

Math.floor("020");   // returns 20
Math.floor("0020");  //returns 20
Number("020");  //returns 20
Number("0020"); //returns 20
+"020"; //returns 20

Problem 2

Problem: Checks for browser-specific conditions being met are repeated throughout the code base (for example, feature detection, checks for supported ES5 features, etc.).

Feedback: Ideally, your code base should be as DRY as possible, and there are some elegant solutions to this problem. For example, you might benefit from the load-time configuration pattern here (also called load-time and init-time branching). The basic idea is that you test a condition only once (when the application loads) and then access the result of that test for all subsequent checks. This pattern is commonly found in JavaScript libraries that configure themselves at load time to be optimized for a particular browser.

This pattern could be implemented as follows:

var tools = {
    addMethod: null,
    removeMethod: null
};

if(/* condition for native support */){
    tools.addMethod = function(/* params */){
        /* method logic */
    }
}else{
    /* fallback - eg. for IE */
    tools.addMethod = function(/* */){
        /* method logic */
    }
}

The example below demonstrates how this can be used to normalize getting an XMLHttpRequest object.

var utils = {
    getXHR: null
};

if(window.XMLHttpRequest){
    utils.getXHR = function(){
        return new XMLHttpRequest;
    }
}else if(window.ActiveXObject){
    utils.getXHR = function(){
        /* this has been simplified for example sakes */
        return new ActiveXObject(’Microsoft.XMLHTTP’);
    }
}

For a great example, Stoyan Stefanov applies this to attaching and removing event listeners cross-browser, in his book JavaScript Patterns:

var utils = {
    addListener: null,
    removeListener: null
};
// the implementation
if (typeof window.addEventListener === ’function’) {
    utils.addListener = function ( el, type, fn ) {
        el.addEventListener(type, fn, false);
    };
    utils.removeListener = function ( el, type, fn ) {
        el.removeEventListener(type, fn, false);
    };
} else if (typeof document.attachEvent === ’function’) { // IE
    utils.addListener = function ( el, type, fn ) {
        el.attachEvent(’on’ + type, fn);
    };
    utils.removeListener = function ( el, type, fn ) {
        el.detachEvent(’on’ + type, fn);
    };
} else { // older browsers
    utils.addListener = function ( el, type, fn ) {
        el[’on’ + type] = fn;
    };
    utils.removeListener = function ( el, type, fn ) {
        el[’on’ + type] = null;
    };
}

Problem 3

Problem: The native Object.prototype is being extended regularly.

Feedback: Extending native types is generally frowned upon, and few (if any) popular code bases should dare to extend Object.prototype. The reality is that there is not likely a situation in which you absolutely need to extend it in this way. In addition to breaking the object-as-hash tables in JavaScript and increasing the chance of naming collisions, it’s generally considered bad practice, and modifying it should only be a last resort (this is quite different from extending your own custom object properties).

If for some reason you do end up extending the object prototype, ensure that the method doesn’t already exist, and document it so that the rest of the team is aware why it’s necessary. You can use the following code sample as a guide:

if(typeof Object.prototype.myMethod != ’function’){
    Object.prototype.myMethod = function(){
        //implem
    };
}

Juriy Zaytsev has a great post on extending native and host objects, which may be of interest.

Problem 4

Problem: Some of the code is heavily blocking the page because it’s either waiting on processes to complete or data to load before executing anything further.

Feedback: Page-blocking makes for a poor user experience, and there are a number of ways to work around it without impairing the application.

One solution is to use “deferred execution” (via promises and futures). The basic idea with promises is that, rather than issuing blocking calls for resources, you immediately return a promise for a future value that will eventually be fulfilled. This rather easily allows you to write non-blocking logic that can be run asynchronously. It is common to introduce callbacks into this equation that execute once the request completes.

I’ve written a relatively comprehensive post on this with Julian Aubourg, if you’re interested in doing this through jQuery, but it can of course be implemented with vanilla JavaScript as well.

Micro-framework Q offers a CommonJS-compatible implementation of promises and futures that is relatively comprehensive and can be used as follows:

/* define a promise-only delay function that resolves when a timeout completes */
function delay(ms) {
    var deferred = Q.defer();
    setTimeout(deferred.resolve, ms);
    return deferred.promise;
}

/* usage of Q with the 'when' pattern to execute a callback once delay fulfils the promise */
Q.when(delay(500), function () {
        /* do stuff in the callback */
});

If you’re looking for something more basic that can be read through, then here is Douglas Crockford’s implementation of promises:

function make_promise() {
  var status = ’unresolved’,
      outcome,
      waiting = [],
      dreading = []; 

  function vouch( deed, func ) {
    switch (status) {
    case ’unresolved’:
      (deed === ’fulfilled’ ? waiting : dreading).push(func);
      break;
    case deed:
      func(outcome);
      break;
    }
  };

  function resolve( deed, value ) {
    if (status !== ’unresolved’) {
      throw new Error(’The promise has already been resolved:’ + status);
    }
    status = deed;
    outcome = value;
    (deed == ’fulfilled’ ? waiting : dreading).forEach(function (func) {
      try {
        func(outcome);
      } catch (ignore) {}
    });
    waiting = null;
    dreading = null;
  };

  return {
    when: function ( func ) {
      vouch(’fulfilled’, func);
    },
    fail: function ( func ) {
      vouch(’smashed’, func);
    },
    fulfill: function ( value ) {
      resolve(’fulfilled’, value);
    },
    smash: function ( string ) {
      resolve(’smashed’, string);
    },
    status: function () {
      return status;
    }
  };
};

Problem 5

Problem: You’re testing for explicit numeric equality of a property using the == operator, but you should probably be using === instead

Feedback: As you may or may not know, the identity == operator in JavaScript is fairly liberal and considers values to be equal even if they’re of completely different types. This is due to the operator forcing a coercion of values into a single type (usually a number) prior to performing any comparison. The === operator will, however, not do this conversion, so if the two values being compared are not of the same type, then === will just return false.

The reason I recommend considering === for more specific type comparison (in this case) is that == is known to have a number of gotchas and is considered to be unreliable by many developers.

You might also be interested to know that in abstractions of the language, such as CoffeeScript, the == operator is completely dropped in favor of === beneath the hood due to the former’s unreliability.

Rather than take my word for it, see the examples below of boolean checks for equality using ==, some of which result in rather unexpected outputs.

3 == "3" // true
3 == "03" // true
3 == "0003" // true
3 == "+3" //true
3 == [3] //true
3 == (true+2) //true
’ \t\r\n ’ == 0 //true
"\t\r\n" == 0 //true
"\t" == 0 // true
"\t\n" == 0 // true
"\t\r" == 0 // true
" " == 0 // true
" \t" == 0 // true
" \ " == 0 // true
" \r\n\ " == 0 //true

The reason that many of the (stranger) results in this list evaluate to true is because JavaScript is a weakly typed language: it applies type coercion wherever possible. If you’re interested in learning more about why some of the expressions above evaluate to true, look at the Annotated ES5 guide, whose explanations are rather fascinating.

Back to the review. If you’re 100% certain that the values being compared cannot be interfered with by the user, then proceed with using the == operator with caution. Just remember that === covers your bases better in the event of an unexpected input.

Problem 6

Problem: An uncached array length is being used in all for loops. This is particularly bad because you’re using it when iterating through an HTMLCollection.

Here’s an example:

for( var i=0; i<myArray.length;i++ ){
    /* do stuff */
}

Feedback: The problem with this approach (which I still see a number of developers using) is that the array length is unnecessarily re-accessed on each loop’s iteration. This can be very slow, especially when working with HTMLCollections (in which case, caching the length can be anywhere up to 190 times faster than repeatedly accessing it, as Nicholas C. Zakas mentions in his book High-Performance JavaScript). Below are some options for caching the array length.

/* cached outside loop */
var len = myArray.length;
for ( var i = 0; i < len; i++ ) {
}

/* cached inside loop */
for ( var i = 0, len = myArray.length; i < len; i++ ) {
}

/* cached outside loop using while */
var len = myArray.length;
while (len--) {
}

A jsPerf test that compares the performance benefits of caching the array length inside and outside the loop, using prefix increments, counting down and more is also available, if you would like to study which performs the best.

Problem 7

Problem: jQuery’s $.each() is being used to iterate over objects and arrays, in some cases while for is being used in others.

Feedback: In jQuery, we have two ways to seamlessly iterate over objects and arrays. The generic $.each iterates over both of these types, whereas $.fn.each() iterates over a jQuery object specifically (where standard objects can be wrapped with $() should you wish to use them with the latter). While the lower-level $.each performs better than $.fn.each(), both standard JavaScript for and while loops perform much better than either, as proven by this jsPerf test. Below are some examples of loop alternatives that also perform better:

/* jQuery $.each */
$.each(a, function() {
 e = $(this);
});

/* classic for loop */
var len = a.length;
for ( var i = 0; i < len; i++ ) {
    //if this must be a jQuery object do..
    e = $(a[i]);
    //otherwise just e = a[i] should suffice
};

/* reverse for loop */
for ( var i = a.length; i-- ) {
    e = $(a[i]);
}

/* classic while loop */
var i = a.length;
while (i--) {
    e = $(a[i]);
}

/* alternative while loop */
var i = a.length - 1;

while ( e = a[i--] ) {
    $(e)
};

You might find Angus Croll’s post on “Rethinking JavaScript for Loops” an interesting extension to these suggestions.

Given that this is a data-centric application with a potentially large quantity of data in each object or array, you should consider a refactor to use one of these. From a scalability perspective, you want to shave off as many milliseconds as possible from process-heavy routines, because these can build up when hundreds or thousands of elements are on the page.

Problem 8

Problem: JSON strings are being built in-memory using string concatenation.

Feedback: This could be approached in more optimal ways. For example, why not use JSON.stringify(), a method that accepts a JavaScript object and returns its JSON equivalent. Objects can generally be as complex or as deeply nested as you wish, and this will almost certainly result in a simpler, shorter solution.

var myData = {};
myData.dataA = [’a’, ’b’, ’c’, ’d’];
myData.dataB = {
    ’animal’: ’cat’,
    ’color’: ’brown’
};
myData.dataC = {
    ’vehicles’: [{
        ’type’: ’ford’,
        ’tint’: ’silver’,
        ’year’: ’2015’
    }, {
        ’type’: ’honda’,
        ’tint’: ’black’,
        ’year’: ’2012’
    }]
};
myData.dataD = {
    ’buildings’: [{
        ’houses’: [{
            ’streetName’: ’sycamore close’,
            ’number’: ’252’
        }, {
            ’streetName’: ’slimdon close’,
            ’number’: ’101’
        }]
    }]
};
console.log(myData); //object
var jsonData = JSON.stringify(myData);

console.log(jsonData);
/*
{"dataA":["a","b","c","d"],"dataB":{"animal":"cat","color":"brown"},"dataC":{"vehicles":[{"type":"ford","tint":"silver","year":"2015"},{"type":"honda","tint":"black","year":"2012"}]},"dataD":{"buildings":[{"houses":[{"streetName":"sycamore close","number":"252"},{"streetName":"slimdon close","number":"101"}]}]}}
 */

As an extra debugging tip, if you would like to pretty-print JSON in your console for easier reading, then the following extra arguments to stringify() will achieve this:

JSON.stringify({ foo: "hello", bar: "world" }, null, 4);

Problem 9

Problem: The namespacing pattern used is technically invalid.

Feedback: While namespacing is implemented correctly across the rest of the application, the initial check for namespace existence is invalid. Here’s what you currently have:

if ( !MyNamespace ) {
  MyNamespace = { };
}

The problem is that !MyNamespace will throw a ReferenceError, because the MyNamespace variable was never declared. A better pattern would take advantage of boolean conversion with an inner variable declaration, as follows:

if ( !MyNamespace ) {
  var MyNamespace = { };
}

//or
var myNamespace = myNamespace || {};

// Although a more efficient way of doing this is:
// myNamespace || ( myNamespace = {} );
// jsPerf test: http://jsperf.com/conditional-assignment

//or
if ( typeof MyNamespace == ’undefined’ ) {
  var MyNamespace = { };
}

This could, of course, be done in numerous other ways. If you’re interested in reading about more namespacing patterns (as well as some ideas on namespace extension), I recently wrote “Essential JavaScript Namespacing Patterns.” Juriy Zaytsev also has a pretty comprehensive post on namespacing patterns.

Conclusion

That’s it. Reviewing code is a great way to enforce and maintain quality, correctness and consistency in coding standards at as high a level as possible. I strongly recommend that all developers give them a try in their daily projects, because they’re an excellent learning tool for both the developer and the reviewer. Until next time, try getting your code reviewed, and good luck with the rest of your project!

(al) (il)


© Addy Osmani for Smashing Magazine, 2011.

Smashing Magazine Feed


The Developer’s Guide To Conflict-Free JavaScript And CSS In WordPress

Posted on by Portsmouth Media in Blog Comments Off

An article I was reading about css3





 



 


sm-wp-css-js

Imagine you’re playing the latest hash-tag game on Twitter when you see this friendly tweet:

You might want to check your #WP site. It includes two copies of jQuery. Nothing’s broken, but loading time will be slower.

You check your source code, and sure enough you see this:

<script src="/wp-includes/js/jquery/jquery.js?ver=1.6.1" type="text/javascript"></script>
<script src="/wp-content/plugins/some-plugin/jquery.js"></script>

What Went Wrong?

The first copy of jQuery is included the WordPress way, while some-plugin includes jQuery as you would on a static HTML page.

A number of JavaScript frameworks are included in WordPress by default, including:

  • Scriptaculous,
  • jQuery (running in noConflict mode),
  • the jQuery UI core and selected widgets,
  • Prototype.

A complete list can be found in the Codex. On the same page are instructions for using jQuery in noConflict mode.

Avoiding the Problem

WordPress includes these libraries so that plugin and theme authors can avoid this problem by using the wp_register_script and wp_enqueue_script PHP functions to include JavaScript in the HTML.

Registering a file alone doesn’t do anything to the output of your HTML; it only adds the file to WordPress’s list of known scripts. As you’ll see in the next section, we register files early on in a theme or plugin where we can keep track of versioning information.

To output the file to the HTML, you need to enqueue the file. Once you’ve done this, WordPress will add the required script tag to the header or footer of the outputted page. More details are provided later in this article.

Registering a file requires more complex code than enqueueing the files; so, quickly parsing the file is harder when you’re reviewing your code. Enqueueing the file is far simpler, and you can easily parse how the HTML is being affected.

For these techniques to work, the theme’s header.php file must include the line <?php wp_head(); ?> just before the </head> tag, and the footer.php file must include the line <?php wp_footer(); ?> just before the </body> tag.

Registering JavaScript

Before registering your JavaScript, you’ll need to decide on a few additional items:

  • the file’s handle (i.e. the name by which WordPress will know the file);
  • other scripts that the file depends on (jQuery, for example);
  • the version number (optional);
  • where the file will appear in the HTML (the header or footer).

This article refers to building a theme, but the tips apply equally to building a plugin.

Examples

We’ll use two JavaScript files to illustrate the power of the functions:

The first is base.js, which is a toolkit of functions used in our example website.

function makeRed(selector){
  var $ = jQuery; //enable $ alias within this scope
  $(function(){
    $(selector).css('color','red');
  });
}

The base.js file relies on jQuery, so jQuery can be considered a dependency.

This is the first version of the file, version 1.0.0, and there is no reason to run this file in the HTML header.

The second file, custom.js, is used to add the JavaScript goodness to our website.

makeRed('*');

This custom.js file calls a function in base.js, so base.js is a dependency.

Like base.js, custom.js is version 1.0.0 and can be run in the HTML footer.

The custom.js file also indirectly relies on jQuery. But in this case, base.js could be edited to be self-contained or to rely on another framework. There is no need for jQuery to be listed as a dependency of custom.js.

It’s now simply a matter of registering your JavaScript using the function wp_register_script. This takes the following arguments:

  • $handle
    A string
  • $source
    A string
  • $dependancies
    An array (optional)
  • $version
    A string (optional)
  • $in_footer
    True/false (optional, default is false)

When registering scripts, it is best to use the init hook and to register them all at once.

To register the scripts in our example, add the following to the theme’s functions.php file:

function mytheme_register_scripts() {
  //base.js – dependent on jQuery
  wp_register_script(
    'theme-base', //handle
    '/wp-content/themes/my-theme/base.js', //source
    array('jquery'), //dependencies
    '1.0.0', //version
    true //run in footer
  ); 

  //custom.js – dependent on base.js
  wp_register_script(
    'theme-custom',
    '/wp-content/themes/my-theme/custom.js',
    array('theme-base'),
    '1.0.0',
    true
  );
}
add_action('init', 'mytheme_register_scripts');

There is no need to register jQuery, because WordPress already has. Re-registering it could lead to problems.

You Have Achieved Nothing!

All of this registering JavaScript files the WordPress way has, so far, achieved nothing. Nothing will be outputted to your HTML files.

To get WordPress to output the relevant HTML, we need to enqueue our files. Unlike the relatively long-winded commands required to register the functions, this is a very simple process.

Outputting the JavaScript HTML

Adding the <script> tags to your HTML is done with the wp_enqueue_script function. Once a script is registered, it takes one argument, the file’s handle.

Adding JavaScript to the HTML is done in the wp_print_scripts hook with the following code:

function mytheme_enqueue_scripts(){
  if (!is_admin()):
    wp_enqueue_script('theme-custom'); //custom.js
  endif; //!is_admin
}
add_action('wp_print_scripts', 'mytheme_enqueue_scripts');

Of our two registered JavaScript files (base.js and custom.js), only the second adds JavaScript functionality to the website. Without the second file, there is no need to add the first.

Having enqueued custom.js for output to the HTML, WordPress will figure out that it depends on base.js being present and that base.js, in turn, requires jQuery. The resulting HTML is:

<script src="/wp-includes/js/jquery/jquery.js?ver=1.6.1" type="text/javascript"></script>
<script src="/wp-content/themes/my-theme/base.js?ver=1.0.0" type="text/javascript"></script>
<script src="/wp-content/themes/my-theme/custom.js?ver=1.0.0" type="text/javascript"></script>

Registering Style Sheets

Both of the functions for adding JavaScript to our HTML have sister PHP functions for adding style sheets to the HTML: wp_register_style and wp_enqueue_style.

As with the JavaScript example, we’ll use a couple of CSS files throughout this article, employing the mobile-first methodology for responsive Web design.

The mobile.css file is the CSS for building the mobile version of the website. It has no dependencies.

The desktop.css file is the CSS that is loaded for desktop devices only. The desktop version builds on the mobile version, so mobile.css is a dependency.

Once you’ve decided on version numbers, dependencies and media types, it’s time to register your style sheets using the wp_register_style function. This function takes the following arguments:

  • $handle
    A string
  • $source
    A string
  • $dependancies
    An array (optional, default is none)
  • $version
    A string (optional, the default is the current WordPress version number)
  • $media_type
    A string (optional, the default is all)

Again, registering your style sheets using the init action is best.

To your theme’s functions.php, you would add this:

function mytheme_register_styles(){
  //mobile.css for all devices
  wp_register_style(
    'theme-mobile', //handle
    '/wp-content/themes/my-theme/mobile.css', //source
    null, //no dependencies
    '1.0.0' //version
  ); 

  //desktop.css for big-screen browsers
  wp_register_style(
    'theme-desktop',
    '/wp-content/themes/my-theme/desktop.css',
    array('theme-mobile'),
    '1.0.0',
    'only screen and (min-width : 960px)' //media type
  ); 

  /* *keep reading* */
}
add_action('init', 'mytheme_register_styles');

We have used CSS3 media queries to prevent mobile browsers from parsing our desktop style sheet. But Internet Explorer versions 8 and below do not understand CSS3 media queries and so will not parse the desktop CSS either.

IE8 is only two years old, so we should support its users with conditional comments.

Conditional Comments

When registering CSS using the register and enqueue functions, conditional comments are a little more complex. WordPress uses the object $wp_styles to store registered style sheets.

To wrap your file in conditional comments, add extra information to this object.

For Internet Explorer 8 and below, excluding mobile IE, we need to register another copy of our desktop style sheet (using the media type all) and wrap it in conditional comments.

In the code sample above, /* *keep reading* */ would be replaced with the following:

global $wp_styles;
wp_register_style(
  'theme-desktop-ie',
  '/wp-content/themes/my-theme/desktop.css',
  array('theme-mobile'),
  '1.0.0'
); 

$wp_styles->add_data(
  'theme-desktop-ie', //handle
  'conditional',  //is a conditional comment
  '!(IEMobile)&(lte IE 8)' //the conditional comment
);

Unfortunately, there is no equivalent for wrapping JavaScript files in conditional comments, presumably due to the concatenation of JavaScript in the admin section.

If you need to wrap a JavaScript file in conditional comments, you will need to add it to header.php or footer.php in the theme. Alternatively, you could use the wp_head or wp_footer hooks.

Outputting The Style Sheet HTML

Outputting the style sheet HTML is very similar to outputting the JavaScript HTML. We use the enqueue function and run it on the wp_print_styles hook.

In our example, we could get away with telling WordPress to queue only the style sheets that have the handles theme-desktop and theme-desktop-ie. WordPress would then output the mobile/all media version.

However, both style sheets apply styles to the website beyond a basic reset: mobile.css builds the website for mobile phones, and desktop.css builds on top of that. If it does something and I’ve registered it, then I should enqueue it. It helps to keep track of what’s going on.

Here is the code to output the CSS to the HTML:

function mytheme_enqueue_styles(){
  if (!is_admin()):
    wp_enqueue_style('theme-mobile'); //mobile.css
    wp_enqueue_style('theme-desktop'); //desktop.css
    wp_enqueue_style('theme-desktop-ie'); //desktop.css lte ie8
  endif; //!is_admin
}
add_action('wp_print_styles', 'mytheme_enqueue_styles');

What’s The Point?

You may be wondering what the point is of going through all of this extra effort when we could just output our JavaScript and style sheets in the theme’s header.php or using the wp_head hook.

In the case of CSS in a standalone theme, it’s a valid point. It’s extra work without much of a payoff.

But with JavaScript, it helps to prevent clashes between plugins and themes when each uses a different version of a JavaScript framework. It also makes page-loading times as fast as possible by avoiding file duplication.

WordPress Frameworks

This group of functions can be most helpful when using a framework for theming. In my agency, Soupgiant, we’ve built a framework to speed up our production of websites.

As with most agencies, we have internal conventions for naming JavaScript and CSS files.

When we create a bespoke WordPress theme for a client, we develop it as a child theme of our framework. In the framework itself, we register a number of JavaScript and CSS files in accordance with our naming convention.

In the child theme, we then simply enqueue files to output the HTML.

function clienttheme_enqueue_css() {
  if (!is_admin()):
    wp_enqueue_style('theme-mobile');
    wp_enqueue_style('theme-desktop');
    wp_enqueue_style('theme-desktop-ie');
  endif; //!is_admin
}
add_action('wp_print_styles', 'clienttheme_enqueue_css'); 

function clienttheme_enqueue_js() {
  if (!is_admin()):
    wp_enqueue_script('theme-custom');
  endif; //!is_admin
}
add_action('wp_print_scripts', 'clienttheme_enqueue_js');

Adding CSS and JavaScript to our themes the WordPress way enables us to keep track of exactly what’s going on at a glance.

A Slight Limitation

If you use a JavaScript framework in your theme or plugin, then you’re stuck with the version that ships with the current version of WordPress, which sometimes falls a version or two behind the latest official release of the framework. (Upgrading to a newer version of the framework is technically possible, but this could cause problems with other themes or plugins that expect the version that ships with WordPress, so I’ve omitted this information from this article.)

While this prevents you from using any new features of the framework that were added after the version included in WordPress, the advantage is that all theme and plugin authors know which version of the framework to expect.

A Single Point Of Registration

Register your styles and scripts in a single block of code, so that when you update a file, you will be able to go back and update the version number easily.

If you use different code in different parts of the website, you can wrap the logic around the enqueue scripts.

If, say, your archive pages use different JavaScript than the rest of the website, then you might register three files:

  • base JavaScript (registered as theme-base),
  • archive JavaScript (registered as theme-archive),
  • general JavaScript (registered as theme-general).

Again, the base JavaScript adds nothing to the website. Rather, it is a group of default functions that the other two files rely on. You could then enqueue the files using the following code:

function mytheme_enqueue_js(){
  if (is_archive()) {
    wp_enqueue_script('theme-archive');
  }
  elseif (!is_admin()) {
    wp_enqueue_script('theme-general');
  }
}
add_action('wp_print_scripts', 'mytheme_enqueue_js');

Using The Google AJAX CDN

While using JavaScript the WordPress way will save you the problem of common libraries conflicting with each other, you might prefer to serve these libraries from Google’s server rather than your own.

Using Jason Penny’s Use Google Libraries plugin is the easiest way to do this. The plugin automatically keeps jQuery in noConflict mode.

Putting It All Together

Once you’ve started registering and outputting your scripts and styles the WordPress way, you will find that managing these files becomes a series of logical steps:

  1. Registration to manage:
    • version numbers,
    • file dependencies,
    • media types for CSS,
    • code placement for JavaScript (header or footer);
  2. Enqueue/output files to HTML:
    • logic targeting output to specific WordPress pages,
    • WordPress automating dependencies.

Eliminating potential JavaScript conflicts from your WordPress theme or plugin frees you to get on with more important things, such as following up on sales leads or getting back to that hash-tag game that was so rudely interrupted.

(al)


© Peter Wilson for Smashing Magazine, 2011.

Smashing Magazine Feed


Faster JavaScript Memoization For Improved Application Performance

Posted on by Portsmouth Media in Blog Comments Off

An article I was reading about plugins

Whilst not new by any means, memoization is a useful optimization technique for caching the results of function calls such that lengthy lookups or expensive recursive computations can be minimized where possible. The basic idea is that if you can detect an operation has already been previously completed for a specific set of input values, [...]
AddyOsmani.com | jQuery & JavaScript Articles For The Community


Essential JavaScript Namespacing Patterns

Posted on by Portsmouth Media in Blog Comments Off

An article I was reading about plugins

In this post, I'll be discussing both intermediate and advanced patterns and approaches for namespacing in JavaScript. We're going to begin with the latter as I believe many of my readers have some prior experience in this area. If however you're new to namespacing with the language and would like to learn more about some [...]
AddyOsmani.com | jQuery & JavaScript Articles For The Community


Avoiding The Quirks: Lessons From A JavaScript Code Review

Posted on by Portsmouth Media in Blog Comments Off

An article I was reading about plugins

I was recently asked to review some code for a new JavaScript application and thought I might share some of the feedback I provided as it includes a mention of JavaScript fundamentals that are always useful to bear in mind. Code reviews are possibly the single biggest thing you can do to improve the overall [...]
AddyOsmani.com | jQuery & JavaScript Articles For The Community


Patterns For Large-Scale JavaScript Application Architecture

Posted on by Portsmouth Media in Blog Comments Off

An article I was reading about plugins

Today we're going to discuss an effective set of patterns for large-scale JavaScript application architecture. The material is based on my talk of the same name, last presented at LondonJS and inspired by previous work by Nicholas Zakas. To continue reading the complete post, click here.
AddyOsmani.com | jQuery & JavaScript Articles For The Community


Building Mobile JavaScript WebApps With Backbone.js & jQuery: Part I

Posted on by Portsmouth Media in Blog Comments Off

An article I was reading about plugins

Welcome to Part 1 of a two-part tutorial on building complete mobile web applications in JavaScript using DocumentCloud's Backbone.js, jQuery Mobile and LABjs. In Part 1, I'll be covering a complete run-down of Backbone 0.5.2's models, views, collections and routers but also taking you through options for correctly namespacing your Backbone application. I'll also give [...]
AddyOsmani.com | jQuery & JavaScript Articles For The Community


The Developer’s Guide To Writing Cross-Browser JavaScript Polyfills

Posted on by Portsmouth Media in Blog Comments Off

An article I was reading about plugins

I believe it is our responsibility as designers and developers to both advocate for best practices and encourage others to make the leap to using modern features for a modern web. At the same time, we need to do our best to avoid leaving users with older browsers behind. Polyfills – a term coined by [...]
AddyOsmani.com | jQuery & JavaScript Articles For The Community


Exploring The Decorator Pattern In JavaScript & jQuery

Posted on by Portsmouth Media in Blog Comments Off

An article I was reading about plugins

Today we’ll be taking a look at the decorator pattern, a structural pattern that promotes code reuse and is a flexible alternative to subclassing. This pattern is also useful for modifying existing systems where you may wish to add additional features to objects without the need to change the underlying code that uses them. Traditionally, [...]
AddyOsmani.com | jQuery & JavaScript Articles For The Community