Category Archives: Coding

Progressive enhancement is still important

By | Coding | No Comments

About 5 years ago it felt like the progressive enhancement battle had been won, but after watching the reactions to Nicholas Zakas’ “Enough with the JavaScript already” it seems all the old arguments are back with reinforcements. Well, I’m wearing my angry-pants and I’m ready for a jog down ranty lane.

This is not about users without JS

If you turn JavaScript off, you’re going to have a tough time on the web. If you remove the steering wheel from your car you’re going to have a tough time going round corners. My advice: Leave the steering wheel where it is.

Progressive enhancement has never been about users who’ve turned JavaScript off, or least it wasn’t for me.

Elevators vs escalators

Christian Heilmann re-purposes a Mitch Hedberg observation to relate to progressive enhancement. Basically, when an elevator fails, it’s useless. When an escalator fails, it becomes stairs. We should be building escalators, not elevators.

Given the diversity of user agents, your JS failing isn’t an edge case. Sometimes it’ll be the browser’s fault, sometimes yours. For example, a few months ago the JavaScript on theDownload Chrome page failed. Y’know what happened when you clicked the “Download Chrome” button? Nothing. A dash of progressive enhancement would have allowed people to continue downloading Chrome while the problem was fixed.

Reduce your testing efforts in older browsers

A couple of years ago I was working on an intranet site for a large company. I built it with progressive enhancement out of habit. The users were mostly on IE7, it was a tightly controlled environment.

Then, at the 11th hour, the client asked for the site to work on Blackberrys, and not the shiny WebKit ones, some of them were using the old Blackberry browser. The site was a disaster on those phones.

However, the ancient Blackberry wasn’t too bad at the ol’ HTML and CSS, but when it came to JS it was a random error generator.

A little (ahem) UA-sniffing later and we weren’t serving JS to the Blackberrys. This got us 90% of the way there, instantly. The rest was just minor CSS tweaks. This was only possible because the site worked without JS. Sure, there were some full-page refreshes that newer browsers did quicker with XHR, and some nice transitions were missing, but it worked.

We took this idea further for Lanyrd’s mobile site where a basic feature detect was used to decide if scripts should be loaded. We didn’t use JavaScript for anything that couldn’t handle ApplicationCache, which was what most of the JS was handling.

The BBC call this basic feature test “Cuts the mustard”. Do yourself a favour, save your JS for the cutting-edge browsers, then you only have to drag the older browsers through HTML & CSS.

It’s important to do this at the script-loading stage rather than just before execution. Not only do you avoid downloading the JS in browsers that don’t need it, but you save on parsing too. On bockety old mobiles, such as the Blackberry, parsing can take many orders of magnitude longer than the downloading, and the UI is blocked while this happens.

Reduce your testing efforts in general

When I make something work on the server, it has to work in Django 1.5.1 running on Python 2.7.3 served through Nginx 1.1.19 etc etc etc. I control the lot, if I change one of the dependencies I can test it before deploying.

Code running on the client is more of a testing effort due to the diversity of interpreter vendors and versions. Unless your server architecture is frequently changing, having most of your logic on the server is easier.

Be faster

JavaScript is more powerful than HTML & CSS, it’s like a Formula 1 car whereas HTML & CSS is a bicycle. However, in a race, the bicycle will get off the line first. An F1 car has a complex start-up procedure and requires a team of people to get it going. If the race is short enough, the bicycle will win.

Here’s how most pages load:

  1. HTML downloads
  2. CSS downloads
  3. CSS fetches additional assets
  4. JS downloads
  5. JS executes
  6. JS fetches additional assets
  7. JS updates DOM

This is the order in which they generally start, 1-4 can happen in parallel to some degree.

In a progressively enhanced page, the whole of step 2 blocks rendering, but other than that the HTML can be parsed and rendered in chunks as it downloads. This is assuming your scripts are async or are at the bottom of the document, which they should be (more on script loading). In this case, step 6 probably isn’t necessary and step 7 is minor.

Also, most modern browsers will take a peek at pages you might open and scans them for things it needs, so there’s a chance the browser already has a head start on downloading the CSS and JS.

In a page that’s entirely JS-driven, as in <body></body>, your first render is blocked by all 7 steps. Sure, your HTML download is tiny, but your JS isn’t, and you don’t get any progressive rendering. If your JS needs to download additional assets, this also blocks rendering and cannot be seen by the look-ahead scanner that can pick up CSS & JS downloads.

JS dependent pages that aren’t simply <body></body> may be able to get some stuff onto the screen sooner, but the page cannot be interacted with until all 7 steps are complete.

But yes, if the race is a bit longer, the F1 car will win. This is why you progressively enhance. You’re off the line straight away on your bicycle, but as the F1 car comes past to overtake, you jump off the bike, do a jaw-dropping backflip in the air, land in the F1 cockpit, and accelerate into the distance.

A great example of this is Twitter, their JS-driven site was painfully slow and clunky. They’re fixing this by switching to progressive enhancement.

Fans of progressive enhancement had a “told you so” moment when Airbnb’s improved performance by delivering requested content as HTML (and sold it as a new idea).

And don’t get me started on blogger.com.

It’s not doubling up on work

There’s a perception that progressive enhancement means building everything on the server then building it again, like for like, on the client. This is rarely the case. Lean on the server as much as possible.

If you want to dynamically update a part of the page, that’s great if it’s actually faster, but do you need client-side templates? Could the server just send you the new HTML for the element? Often, yes. Remember, HTML is a semantic data format just like JSON, and if you’re simply going to convert that JSON to HTML on the client, just do it on the server.

If you need client-side templates, use a format that can be shared with the server, such asMustache. Even then, consider compiling the templates to JavaScript functions on the server and serve those, saves every client having to do the parsing & compilation.

Work with the browser, not against it

Lanyrd’s mobile site is built the progressive enhancement way, but we used JavaScript to handle all page-to-page navigation (similar to using XHR to bring the new content in). This was to hack around limitations in AppCache, and it came at a cost.

So, you click on a link, JS changes the content. At this point, the URL isn’t reflecting the content. That’s ok, we have history.pushState(). Then the user clicks the back button, we pick up the URL change and switch the content back. However, this doesn’t feel natural because the user is sent back to the top of the page, whereas expectation is to restore the scroll position. Ok, so now we have to record scroll positions before we change content, and work out the conditions for when scroll position should be restored.

The more you take over from the browser, the more complex yet expected browser behaviour you have to reimplement in JavaScript. And if different browsers do different thing, you pick one behaviour & it feels odd to users who aren’t used to it.

“App” is not an excuse

“Yeah, but I’m building a webapp, not a website” – I hear this a lot and it isn’t an excuse. I challenge you to define the difference between a webapp and a website that isn’t just a vague list of best practices that “apps” are for some reason allowed to disregard. Jeremy Keith makes this point brilliantly.

For example, is Wikipedia an app? What about when I edit an article? What about when I search for an article?

Whether you label your web page as a “site”, “app”, “microsite”, whatever, it doesn’t make it exempt from accessibility, performance, browser support and so on.

If you need to excuse yourself from progressive enhancement, you need a better excuse.

There are, of course, exceptions

…but they must be exceptions. SpriteCowJank Invaders and Request Quest all depend on JS.

SpriteCow could be done server-side, but it’s a rare case where the client can totally outperform the server due to the transfer of image data.

Jank Invaders is basically a demo of a JavaScript feature, and like many games simply doesn’t have a sensible server-side fallback.

Request Quest depends on JavaScript because it’s… well… it has to process… yeah ok, I just got lazy. Don’t do that!

One of the best things about the web is it can rival native applications without a hefty initial download, without an install process, and do so across devices old and new. Let’s keep it that way.

Edit: Emil Björklund wrote a similar post yesterday that’s worth reading. Another edit: Emil’s server appears to be down at the moment, not even progressive enhancement can save us from that.

source: Jake Archibald

HTML role attributes

By | Coding | No Comments

Introduced as part of XHTML, they mark the functionality or orientation of a give content. Used by WAI-ARIA capable screen readers to deduct content from the page. Example:

<div role=”banner”>This is my banner</div>

This is supposed to be more semantic than <div class=”banner”>

There are a bunch of roles that can be used (you can’t make them up):

banner

This is a region that contains the prime heading or internal title of a page. Most of the content of a banner is site-oriented, rather than being page-specific. Site-oriented content typically includes elements such as the logo of the site sponsor, the main heading for the page, and the site-specific search tool. This typically appears at the top of the page, spanning the full width.

complementary

This is any section of the document that supports but is separable from the main content, yet is semantically meaningful on its own even when separated. There are various types of content that conform to this role. For example, take the case of a portal—this may include but not be limited to show times, current weather, related articles, or stocks to watch. The content should be relevant to the main content; if it is completely separable, a more general role should be favored.

content

infoThis is meta information about the content on the page, or the page as a whole. For example, footnotes, copyrights, links to privacy statements, and suchlike would belong here.

main

As the name suggests, this is the main content in a document. It marks the content that is directly related to or expands upon the central topic of the page.

navigation

This refers to the collection of links suitable for use when navigating the document or related documents.

note

This denotes content parenthetic or ancillary to the main content of the resource.

search

The search tool of a web document, this is typically a form used to submit search requests about the site or to a more general internet search service.

A quick glance at these values shows considerable overlap between many of the new HTML5 elements; the banner role and header element, complementary role and asideelement, navigation role and nav element, all seem very closely related. Indeed, thecomplementary and note roles in combination cover the purpose of the aside element. We saw that the aside element has been stretched to include two quite different purposes; arguably having two separate roles (or elements, in HTML5 ) would make more sense.

The main role also arguably provides a purpose for which HTML5 does not have an element—the main content block of a page.

Now, unlike with class or id, you can’t simply invent your own role values. It is possible to define your own role values formally, though in most instances this will be of no practical value as browsers and other software won’t have any idea of what to do with it, and in any case it’s beyond the scope of this course. However, as you might have guessed, ARIA defines a number of additional values in addition to the standard role values defined in XHTML 1.1. ARIA roles can be quite complex, so let’s focus on some of the most immediately useful ones. Note also that simply adding a role value to an element (for example, role=”button” to a span element) doesn’t make that element a button. Rather, role is for describing the purpose for which you are using the element. It’s up to the developer to make the span behave like a button.

ARIA defines several types of role, among these widget roles (we saw earlier that a widget is what ARIA calls controls), landmark roles (regions of the page intended as navigational landmarks) and document structure roles (structures that organize content in a page). Next up, let’s run through a quick overview of the most common ARIA roles.

Widget Roles

Widget roles include:

  • alert
  • alertdialog
  • button
  • checkbox
  • combobox
  • dialog
  • marquee
  • menuitem
  • menuitemcheckbox
  • menuitemradio
  • option
  • progressbar
  • radio
  • scrollbar
  • slider
  • spinbutton
  • status
  • tab
  • tabpanel
  • textbox
  • timer
  • tooltip
  • treeitem

Landmark Roles

Landmark roles include:

  • banner
  • complementary
  • contentinfo
  • main
  • navigation
  • search

Document Structure Roles

Document structure roles include:

  • article
  • group
  • heading
  • list
  • listitem
  • note
  • presentation
  • separator

source: Knowledge Base

Become a Better, Faster Front-End Developer

By | Coding | No Comments

So you’re a pretty great web developer already.

You’ve got some killer CSS chops (cross browser even), perhaps you’ve been a Photoshop expert for years, and you’ve got enough jQuery knowledge to make almost any chained animation go smoothly.

But certainly you ask yourself, what’s next?

In fact, one of the most asked questions about web development is, “how do I stay on the leading edge?” Chris Coyier recently presented a fantastic talk on the subject, and there are sites fully dedicated to staying up to date on the latest web design news. Addy Osmani’s roundup on becoming a better front-end engineer sets some great content out on the board for you to consider on the subject; needless to say, a lot of smart people are thinking about this very subject, so you’re headed in the right direction.

better-full 
Space Ghost wallpaper, by Mads Frantzen

In this article, we will talk about a very important way to set yourself apart and become a better developer: becoming an effective rapid interaction developer.

What is “Rapid Interaction Development?”

Rapid interaction development is a term we’re using today to describe the practice of rapidly creating something for the web that a user can interact with, specifically with an intention to quickly iterate and polish the interaction. This is not the same thing as designing flat documents; instead, this includes building something that has one or more storylines of interaction.

This may include, for instance, a widget that the user can type into and search, or a dropdown menu that allows a user to select a sub-menu item. These interactive pieces are the building blocks of a larger storyline of the user’s full experience of using a website, and thus they are incredibly important to be able to iterate through and “feel”. When designing a website, these interactions can make or break the user’s experience, and thus could make or break the effectiveness of the site as a whole.

Interactions don’t always have “moving” pieces; in fact, rapid interaction development often relies on content hierarchies and hyperlinks as much as anything else. Interaction development takes into account the full interaction of the human with the computer, incorporating intuitions about the userbase, basic understanding of human factors, and a knowledge of the message and image of the organization or individual represented by the interaction.

Understanding the Value of Rapid Interaction Development

If I am hiring a front-end web developer (or anyone for that matter), I will be thinking about five primary things.

  1. Does their personality fit my team?
  2. Are they talented?
  3. Are they efficient?
  4. Are they consistent?
  5. Can I pay them properly?

These questions are extremely important to any part of the hiring process. The first question is usually decided based off of interaction chemistry – not something we are going to cover in this article. The fifth is usually decided on a case-by-case basis, and is also something that is outside the scope of this article. However, when answering the other three questions, two primary factors play into the judgement: speed and accuracy. In the case of the web developer, rapid interaction development is a way of proving that you have take the craft of interaction development very seriously.

Rapid interaction development isn’t accidentally fallen upon when a muse strikes (as may be the case with a more art-driven degree). Instead, rapid interaction development is a skill that is honed by the developer. This skill proves efficiency and talent, and gives more confidence in the developers ability to achieve consistency. To be able to rapidly develop interactions, the developer must have the two magic ingredients: speed and accuracy.

A disclaimer: It may be that someone gets hired because, though they aren’t as talented as another individual, they are extremely consistent and have a great personality. This by no means is a “how to get a job as a developer” guide.

Let’s Get On With It, Shall We?

With the understanding of the importance of rapid interaction development, we now can understand how you can immediately begin to hone this skill. Some of these tips take a simple change in mindset, while others take an investment of learning or pattern change. All of these, however, can help you become a better, faster, more valuable web developer.

Optimize Your Patterns

Have you adopted a CSS framework? If so, then you understand the value of reusable code. You have most likely adopted patterns without realizing it. In order to prove this, ask yourself, “when I start to build a website, what is my first step?” If your answer is “I don’t know”, then it’s time to figure it out. If your answer is “first I open my text editor”, then you’ve adopted at least one step in a pattern.

So, how do you optimize a pattern? These are often called workflows, but that’s not an adequate description, as workflow doesn’t include everything we want to talk about here. Some common tools to help you structure your pattern are CSS and JS “frameworks” like Twitter BootstrapFoundation, orTopcoat..

rapid-foundation

..preprocessing tools like SASS or LESS..

rapid-less

..perhaps full optimization and processor tools like CodeKit..

rapid-codekit

..startup WordPress themes like Bones, and even the option of building customized scripts powered by a command line. If you’re a more advanced JavaScript developer and are looking to move into a new space, you should consider looking at BackboneEmber, and other (MVC-oriented JavaScript frameworks)[http://todomvc.com/]; it would also be advised to look intoNode, which empowers server-side JavaScript. It may take you some time, but picking up and learning some of these tools certainly increases productivity in the long run.

Recommendation: decide on some kind of HTML boilerplate/reusable “index.html” document and associated file structure that follows commonly accepted conventions, is built with semantic markup, and gives a “blank slate” to work from (think: HTML5 Boilerplate). Perhaps if you work primarily with WordPress or another tool, you’d want to find a similar boilerplate with base-level functionality for that tool.

If you’re a bit more advanced, pick up some Yeoman skills for fast project scaffolding and wizard-based boilerplate generation. Decide on a CSS and/or JS framework (Bootstrap, Foundation, Topcoat), and start using a preprocessor for CSS sooner rather than later. Learning a preprocessor is well worth the time investment, and won’t reduce productivity as LESS and SASS can both handle vanilla CSS. Try building a full wireframe of a basic layout completely with a framework’s built-in classes. You’ll likely be surprised how little code you need to write to make a functional layout happen very quickly. This reduces the overhead of writing repetitive code and also has the added benefit of pulling from much more extensive testing and cross-browser considerations than one person can do on their own.

Work With What you Know; Intentionally Learn What you Don’t.

It’s absolutely important to adopt a lifestyle of learning as a developer. Adopting new tools and skills like those discussed above is a part of the lifeblood of any successful developer. The technology we are using every day is changing faster than anything else; in order to stay at or above our current place in the industry, it is imperative that we learn continuously.

But – it is also as important to understand that learning new technology will slow you down – at first. For this reason, when you are practicing rapid interaction iteration, you shouldn’t also be learning a new framework. Instead, intentionally take some time out of your week and dedicate it to learning that framework through a pet project, weekend hack night, or by implementing pieces of the new tool in a project that absolutely needs the new functionalities provided by that solution. This will allow you to maintain your momentum, and solve problems fluently rather than in a stop-go Google and StackOverflow binge. Most importantly, this intentional segregation allows you to focus on what matters: solving design problems instead of code bugs.

As a secondary note, when you are intentionally learning, it also helps to solve problems that already have well-known and well-documented solutions; of course, the world doesn’t need another simple to-do application. But creating a to-do application may help you understand JavaScript much more, and may help you in the future when you are synthesizing information in order to solve new problems. Building solutions for problems that already have well documented solutions helps you compare and contrast your solution, and makes it easier to search for help when you get stuck. If you are in uncharted territory and trying to learn at the same time, getting lost is much more likely, and will detract from the goal of the learning process.

Adopt Hyperfocused Mini-Sprints

If you’ve heard the term “agile”, you might have some idea of what a sprint is. Sprints are short, pre-defined work periods where developers decide on a set of goals, and “sprint” to finish those goals within the alotted amount of time. Because we are talking about rapid interaction development, a sprint is well suited to this discussion. Here are the basics.

  1. DefinePrioritize tasks/goals, define the length of the sprint, remove or add tasks until the estimated amount of time to complete the tasks matches the predefined length of the sprint
  2. SprintThis is time where you are “in the zone” – zero distractions, etc.
  3. ReflectOnce the sprint is complete, check your progress. Did you meet or exceed your goals? What caused the most hangup?
  4. AdaptLearn from what you reflected on, and put systems into place to help avoid the hangups.

In the traditional agile approach, sprints are based on helping with team collaboration and generally last multiple days or even weeks. Here, we are talking about self-management and hyperfocused mini-sprints. These mini-sprints might even simply focus on a single task or interaction, and its associated goals. The process of defining and prioritizing the task or its subtasks before diving into the work, and subsequently taking time to reflect on the process and adapt your workflow or patterns (remember, it’s important to optimize your patterns) will help you become more objectively aware of your speed and productivity, and will allow you to be more conscious of what could use improvement at a micro-level.

Recommendation: define two 3 hour sprints for one day, each with a primary task. The purpose of the sprint (as with a physical sprint) is to drive your brain as hard as you can for those 3 hours. After those 3 hours, you will need a brain break; perhaps this is your lunch break, or maybe you’ve chosen to adopt an alternative schedule to allow for an uninterrupted hyper-focused block of time (more on that later). Whatever the case, planning these sprints apart from each other will help you recharge your brain. It’s worth trying completely opposite types of activity (like taking a walk or reading fiction) or even a nap – more on that here. If you work for an agency, perhaps the break in between is the time you set aside for meetings, administrative tasks, or less taxing development tasks. Some people consider this the best way to work every day, and some may choose to do this kind of “sprint interval training” sporadically; choose what ends up making you the most productive, and increases your interaction development speed.

Temporarily Block Go-To Websites

If you are like most people, your fingers have muscle memory; when you open a browser, is it instinct to immediately type in Hacker News, Tuts+, or Twitter? What are the sites that cause you to procrastinate?

rapid-let_go

Hacker News has attacked this problem in a specific way, offering signed-up users the ability to set up a “noprocrastinate” restriction. There are some interesting tools that also offer these kinds of restrictions, but why not do it yourself? On a Mac, run the following commands from terminal:

sudo nano /etc/hosts
# enter your password when it asks for it.
# This will open a file in a terminal-based code editor;
# Don't worry! You won't be doing much in here. Type the following lines.

0.0.0.0 twitter.com
0.0.0.0 facebook.com

# press Ctrl+C (exit), Y (yes I'd like to save), and enter (save as the existing filename)
rapid-console

You can edit the same file on Windows (see this explanation).

This will block you from using Twitter or Facebook, and will instead redirect you to your localhost (0.0.0.0 is a shortcut to your machine). To get back to social-network-land, just follow the same steps, but remove the lines you added.

Recommendation: Should you block Facebook and Twitter all the time while you are working? We say no. It makes sense to be able to take small breaks between tasks to keep from burning out. However, during a sprint, if these sites are seemingly causing you to waste time, it’s important (at least until you break the muscle-memory driven habit) to put them on pause. The important note here is, control your procrastination, even if that means scheduling time to waste. Being aware of the time you are putting into a given activity will help you be more conscious of whether or not that time is slipping away from your control.

Minimize Interruption

Interruptions have long been known to decrease productivity of knowledge workers. (See herehereherehere – and there is much more available through a quick Google search.) Programmers (and, therefore, web designers) are susceptible to potentially only getting one uninterrupted 2-hour session in a day. In agile methodology, there is the concept of core hours that holds that strong focus should be maintained for 5 total hours per day. This is a far jump from the two hours programmers can expect to achieve in a normal office.

The Anatomy of an Interruption

There are many kinds of interruptions, but we will look at two specific aspects of interruption today. The first are welcomed or “self-inflicted” interruptions, the second are external or “intrusive” interruptions. Both types are detrimental to productivity, and both types can be somewhat managed in different ways.

Self inflicted interruptions occur because you have in some way created space for them to occur. These usually come in the form of programmable notifications (phone, computer, etc).

rapid-push

Intrusive interruptions occur because other humans need you to pay attention to them. The disconnect is the timing and sense of urgency. You must manage your own time, and you must put into place ways of doing so that circumvent the negative effects of interruption as much as possible.

So what do you do to alleviate interruptions? How do you achieve Zen Zone Time? Here are a few of our recommendations.

  1. Minimize or completely disable notificationsThis includes phone notifications like texts, email, Twitter, and even “chat”. Hide your chat windows, and attend to them as a part of your workflow, instead of on a response “demand” basis. This may seem like it will hurt your productivity at first, but you might be surprised how willing people are to wait if it is actually important, and how likely they are to problem solve for themselves if you are too busy to break from what you are doing.
  2. Have your management read this: adopt an organizational respect for The Zone.Create rules in the organization about “zone time” or “maker time”. This means there are specific boundaries for when, where, and how you can interrupt someone when they are in the zone. Have specific ways of signifying you are “under”, like putting your headphones in or working in a specific part of your office. This is the purpose of “away” messages on chat, as well. Management must set aside time for the cultivation of rapid interaction development!
    Managers – this may seem like a potential threat to the office, but like anything, you can try this for a bit to see what pieces fail and what pieces succeed. You will likely see productivity increases immediately.
  3. Isolate yourselfPerhaps the most effective solution, isolating yourself makes you the controller of your space. This can happen in many different formats; for instance, many web designers and developers work from coffee shops to dive into isolation. This will prevent interruptions that happen as a result of physical proximity. Isolation doesn’t always mean location, however; if most of the office works from 9-5, perhaps you work from 6AM to 2PM or 12PM to 8PM. This will give you space and time to think and work without interruption. Perhaps you can work remotely one or two days per week? Maybe it’s much simpler than that for you, particularly if you are a freelancer.
  4. Be diligent with scheduled communicationIf you are going to put barriers up around you, you must also be willing to stick to your word and respond to messages when you come out from under the Zone. Don’t let this slip, or else the productive aspects of your Zone time will be reduced by the negative aspects of your communication habits. Oh, and don’t forget to call your mother!

Game On: Competition and Reward

What makes “hackathon” events so productive? How do people turn out viable products in 48 hours? Perhaps it is a mixture of characteristics.

  1. Anticipated, protected, planned time for focused rapid development
  2. Competition with others
  3. Cash rewards

Hackathons break from the “normal flow” of every day work. Certainly, we wouldn’t want to work 48 hours in a row all the time. But the productivity mindsets that arise from this are extremely important. We’ve alluded already to how important focus and uninterrupted time is. However, it’s a worthy effort to consider how creating some personal competition and reward systems may help increase your efficiency in development. This helps set benchmarks and naturally trains your brain to adapt to the behaviors that are rewarding.

Recommendation: if you work with another developer, decide on a competition with clear goals, and make it time oriented. Doesn’t really matter what those goals are. Take some time to work through them. Perhaps you can compete against yourself; practice by using the sprints as your competition, and set your goals to increase your efficiency by some amount of time. Set rewards up both for when you are in a competitive mode, as well as for when you complete any focused sprint of work. This will help keep you focused during the sprint itself. A reward may be a physical thing (like a cup of coffee) or something less concrete (like a VIP parking spot for a week or “free time”).

Dive into the Open Source Community

We will keep this tip short, because the benefits here will be obvious. The Open Source World is full of amazing and talented people building things that help others do their jobs better every day. Examples like the frameworks we mentioned above just barely scratch the surface. Here are some of the benefits to working and communicating with the open source community.

  1. Exposure to new tools
  2. Free solutions to common problems
  3. New solutions to emergent problems
  4. A better understanding of problems you may not know exist
  5. Opportunity to contribute and become a part of the giving/receiving cycle
  6. Thought Osmosis: learning by repetition and exposure

Diving into the open source community and learning to use tools that are offered can immediately increase productivity, but also makes it much more likely that another person could pick up your project and continue developing on that project. Open source allows for people to collaborate around a decided standard and pre-existing documentation. This reduces cognitive overhead for transfer of projects, and makes you a much more literate developer; this immediately translates into higher efficiency.

Recommendation: Get a GitHub account, and start building things with tools available on GitHub.

rapid-gh

This is somewhat of a reiteration of what we said earlier – use open source frameworks to solve problems in predictable, patterned ways, and participate in the community of other people who are doing so. Collaboration and discussion are very important keys to learning.

Conclusion

This by no means is a complete list of things you can do to become a rapid interaction developer. Leave some notes in the comments of things you’ve tried that have worked, failed, or have had little to no effect!

source: tuts+

CSS Typography cheat sheet

By | Coding | No Comments

Small roundup on CSS features that will enhance your web typography.

Today I want to write about a few small typography enhancing features in CSS. Most of them don’t seem to be inside the mainstream CSS wisdom floating around (perhaps I am just missing them constantly :(…). So I decided to give them a quick shout out so more of you guys can make use of them.

Font-face irritation

First I wanted to highlight a small font-face irritation I often see these days. Most people add custom fonts via font-face using unique names for every font weight. That’s not necessary & will save a lot of small headaches if you do it right from the beginning. You can add multiple weights & styles for every font & use the same font name. Let me give you code example:

@font-face {
     <a href="http://docs.webplatform.org/wiki/css/properties/font-family" target="_blank">font-family</a>: 'Liberation Sans';
     <a href="http://docs.webplatform.org/wiki/css/properties/src" target="_blank">src</a>: url('fonts/LiberationSans-Regular.ttf') format('truetype');
     <a href="http://docs.webplatform.org/wiki/css/properties/font-weight" target="_blank">font-weight</a>: normal;
     <a href="http://docs.webplatform.org/wiki/css/properties/font-style" target="_blank">font-style</a>: normal;
}
@font-face {
     <a href="http://docs.webplatform.org/wiki/css/properties/font-family" target="_blank">font-family</a>: 'Liberation Sans';
     <a href="http://docs.webplatform.org/wiki/css/properties/src" target="_blank">src</a>: url('fonts/LiberationSans-Italic.ttf') format('truetype');
     <a href="http://docs.webplatform.org/wiki/css/properties/font-weight" target="_blank">font-weight</a>: normal;
     <a href="http://docs.webplatform.org/wiki/css/properties/font-style" target="_blank">font-style</a>: italic;
}
@font-face {
     <a href="http://docs.webplatform.org/wiki/css/properties/font-family" target="_blank">font-family</a>: 'Liberation Sans';
     <a href="http://docs.webplatform.org/wiki/css/properties/src" target="_blank">src</a>: url('fonts/LiberationSans-Bold.ttf') format('truetype');
     <a href="http://docs.webplatform.org/wiki/css/properties/font-weight" target="_blank">font-weight</a>: bold;
     <a href="http://docs.webplatform.org/wiki/css/properties/font-style" target="_blank">font-style</a>: normal;
}
@font-face {
     <a href="http://docs.webplatform.org/wiki/css/properties/font-family" target="_blank">font-family</a>: 'Liberation Sans';
     <a href="http://docs.webplatform.org/wiki/css/properties/src" target="_blank">src</a>: url('fonts/LiberationSans-BoldItalic.ttf') format('truetype');
     <a href="http://docs.webplatform.org/wiki/css/properties/font-weight" target="_blank">font-weight</a>: bold;
     <a href="http://docs.webplatform.org/wiki/css/properties/font-style" target="_blank">font-style</a>: italic;
}

Notice that every font-face addition got the same name, but has different attributes for font-weight & font-style. This way you can go ahead & use your font the same as you would with any native font.

Bold, strong or italic are now already defined & should just work out of the box, without extra CSS code. I used to declare every font-weight with its own name (like Droid-Bold) & had to add it via CSS to every possible tag that could cause my font to display the bold variant. With this new way to write font-face, this isn’t necessary anymore.

Hyphenation

Hyphenation is the better word-break. It’s locale aware, and inserts the hyphen character at the correct place, when breaking the words. This is especially important in responsive designs. It will save you from a lot of ragged lines. And, no need anymore for clunky & slow Javascript hyphenation fallbacks. Jackpot!

Sadly we still need to prefix them:

-webkit-hyphens: auto;
    -moz-hyphens: auto;
         <a href="http://docs.webplatform.org/wiki/css/properties/hyphens" target="_blank">hyphens</a>: auto;

For definite cross browser support you need to inject this weird code snippet:

             -ms-word-break: break-all;
                 word-break: break-all;

                 // Non standard for webkit
                 word-break: break-word;

            -webkit-hyphens: auto;
               -moz-hyphens: auto;
                    hyphens: auto;

   -webkit-hyphenate-before: 2;
    -webkit-hyphenate-after: 3;
            hyphenate-lines: 3;

The Hyphenate-Before or -after sets a minimum number of characters before or after the hyphenation. And hyphenate-lines how many lines can be hyphenated in a row. As you may have guessed, these are Webkit only.

For more information check out the W3C Hyphens Definition & for browser compatibility take a look atHyphens on Can I Use

OpenType Ligatures

I love this one.

The vast majority of fonts contain lowercase and uppercase alphabets, numerals, punctuation and accents. But there can be much more to fonts than this basic set of characters. Many professionally-designed fonts also contain ligatures, alternative characters, smallcaps, different kinds of numbers, and sometimes much more besides. These lines of code enable your fonts to really shine (as long as they feature a few of these OpenType features). This is how you enable it:

h1 {
    -moz-font-feature-settings: "liga=1, dlig=1";
    -ms-font-feature-settings: "liga", "dlig";
    -webkit-font-feature-settings: "liga", "dlig";
    -o-font-feature-settings: "liga", "dlig";
    font-feature-settings: "liga", "dlig";
}

This way you turn on ligatures, as well as discretionary ligatures. For more info into ligatures & OpenType features check out this FontShop explanation.

Adjusting font sizes for fallback fonts

If you are using font stacks, this one is for you.

In situations where font fallback occurs, fallback fonts may not share the same aspect ratio as the desired font family and will thus appear less readable. The font-size-adjust property is a way to preserve the readability of text when font fallback occurs. It does this by adjusting the font-size so that the x-height is the same regardless of the font used.

.adjust {
    font-size-adjust: auto;
}

You can use the following values to define the adjustment: none, auto & a number. I would recommend sticking to auto. It works fine for me. For more information on this topic, check out the W3C documentation.

source: NewNet Soft

Stop doing internet wrong

By | Coding | No Comments

Some days…some days it’s frustrating to be on the web. We’re compiling C++ into JavaScript and running Unreal in the browser but at the same time, here in 2013, we’re still making the same mistakes. And by we, I mean, the set of web developers who aren’t us, right Dear Reader? Because surely you’re not doing any of these things. 😉

All of these are solvable problems. They aren’t technically hard, or even technically interesting. I consider these “will-required” problems. You need the knowledge that it’s wrong and the will to fix it. As users – and web developers – we need to complain to the right people and help fix it.

REDIRECTING A DEEP DESKTOP LINK TO A MOBILE HOME PAGE

Google has decided that the practice of taking perfectly good deep links like foo.com/something/deep, detecting a mobile device, then redirecting to m.foo.com is user-hostile. In fact, the GoogleBot is going to declare these “faulty redirects” and ding sites in the search result ranking. Stated simply:

Avoiding irrelevant redirects is very easy: Simply redirect smartphone users from a desktop page to its equivalent smartphone-optimized page. If the content doesn’t exist in a smartphone-friendly format, showing the desktop content is better than redirecting to an irrelevant page.

For example, if I want to go to the http://www.mcmenamins.com/Pubs page, but I do it on mobile, they ALWAYS redirect me to /mobile. Always. Even though I have a quad-processor pocket supercomputer with gigs of space I’ve still surfing a second-class internet.

image image

I DON’T WANT YOUR CRAPPY APP

That means you Quora. I am in my browser, unless I’m going to the App Store, let’s assume if I’m in the browser, I want to be on the web.

You suck Quora

GIANT INTERSTITIAL ADS

I’m looking at you, Forbes.com. I GET IT. YOU HAVE ADS.

Interstitial Ads are Evil

Stay classy.

LABELS FOR INPUT FORMS

I hate seeing a checkbox and only being able to click on that exact checkbox.

<p>Which fruit would you like for lunch?</p>
<form>
  <input type="radio" name="fruit" id="banana" />
  <label for="banana">Banana</label>
  <input type="radio" name="fruit" id="None" />
  <label for="none">None</label>
</form>

It’s so easy to just associate a label with an input. Please do  it, then we can all have something larger to click on.

BREAKING HYPERLINKS

We’re still doing this. Haven’t we learned that Cool URIs Don’t Change? It was true in 1998 when that was written and it’s true now. The web as we know it was created in 1990 and made truly open in 1993 and the link to the First Web Page (yes, Capital Letters) is still http://info.cern.ch/hypertext/WWW/TheProject.html. I love that they’ve done the work to keep that link alive.

There’s just no excuse for this. With .htaccess files and web.config files, maintain a list of redirects and do your best to test them. Maintaining deep and complex links can be complex, but if you’re companyname.com/about link dies because you switch from PHP to Rails, there’s just no excuse for that. I’m your User and I have always typed /about. Don’t’ give me a To Do like “Update your bookmarks!” I didn’t come here for a To-Do, I came her for your damn about page. YOU figure it out.

image

CLICK THE FLAG THAT REPRESENTS YOUR LANGUAGE

I’ve often been asked to “select my language” from a list of country flags, and ended up clicking on the Union Jack to represent “English.” I’m sure the actual English don’t appreciate an American declaring they speak English. 😉

Nothing says pick a language like all the United Nations Flags

but I know I’m not the only one who realizes that a Flag is a lousy representation of a language, especially since your browser is announcing what languages you speak with every web request.

Accept:text/html
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8

There can be a whole list of languages in the Accept-Language header, in the order the user prefers them!  Use that data, it’s there for you to use.

YOU KNOW MY ZIP CODE, WHY AM I ENTERING MY STATE?

For folks living in the states, we’re always asked to enter our postal code (ZIP code) and our city and state, even though there are dozens of great APIs and Databases that can give you that information.

Don't make me enter my state

The meta-point is this: If you can reliably determine something from the user (language, location, country, preference) without invading their privacy, do it! Save them a little time!

RESIZING GIANT IMAGES WITH WIDTH AND HEIGHT ATTRIBUTES

Perhaps take a moment and remind your boss that the 6 megapixel photo that he or she took with their new Canon EOS is not a good background image for your corporate site…especially if it’s a 4 megabyte JPGs.

Oh, that’s OK, we can just <img src=”bigassfile.jpg” width=”100″ height=”100″> and that will make it smaller. No, that just downloads the giant file and then makes your browser do the work to resize it on the client.

Big ass picture

Resize first, and squish often. Also run all your PNGs through PNGGauntlet or PNGOut.

SERVING PAGES FROM BOTH WWW. AND NAKED DOMAINS

If you’ve got example.com/something AND www.example.com/something both serving up the same content, consider “canonicalizing” your URLs. You can do this with rel=”canonical” in your META tags, but that only hides the problems and makes the Googlebot happy. Instead, why not PICK ONE and serve a 301 redirect to the other? Did you know that there are rules built into IIS7 that will set this up for you? You can even remove your .aspx extension if that makes you happy. You can do it!

image

The same is true if you do the same thing for / and /default.html. Pick one if you can, and redirect the other.

<system.webServer>
    <rewrite>
      <rules>
        <rule name="CanonicalHostNameRule1" stopProcessing="true">
          <match url="(.*)" />
          <conditions>
            <add input="{HTTP_HOST}" matchType="Pattern" pattern="^hanselman\.com$" ignoreCase="true" negate="false" />
          </conditions>
          <action type="Redirect" url="http://www.hanselman.com/{R:1}" redirectType="Found" />
        </rule>
          <match url="blog/default.aspx" />
          <action type="Redirect" url="blog/" redirectType="Found" />
        </rule>
      <rules>
   <rewrite>
<system.webServer>

source: Scott Hanselman

7 Awesome Emmet HTML Time-Saving Tips

By | Coding | No Comments

emmetEmmet, formerly Zen Coding, is one of the most downright practical and productive text editor plugins that you will ever see. With its ability to instantly expand simple abbreviations into complex code snippets, Emmet makes you feel like a powerful coding wizard with the world at your fingertips.

As a follow up to our previous article on the basics of Zen Coding, today we’re going to dive into seven awesome tips to help you become a true Emmet pro.

1. Skip the Div

Our first tip is that you rarely need to type out “div” in your macro. It’s tempting because that’s what you do with every other HTML element, but divs are special and actually require even less effort. All you have to do is type out an ID (using a hashtag) or a class (using a period) and Emmet will assume that you’re looking to create a div.

screenshot

As you can see, both abbreviations yield the same result. Since Emmet is all about saving you time by reducing the amount of typing required, always shoot for the shortest route to what you want.

Implicit Tag Names

This quirk is actually part of a greater feature called “implicit tag names”, which attempts to interpret the tag that you want based on context. Notice that I don’t type out either “div” or “li” in my abbreviation, but they are assumed and inserted into the final expanded snippet.

screenshot

2. Chain Abbreviations With DOM Navigation

If you’re using Emmet to expand simple class names into divs, good for you, you’re off to a decent start. The real time saving power though is only reached once you learn to effectively build larger macros that can expand into a significant portion of your markup.

The key to this is to memorize and understand the syntax that will help you branch off into different levels of your document tree. There are three important symbols to keep in mind:

screenshot

As you can see, “>” allows you to go deeper into the tree and create a child, “+” allows you to create a new element on the same level as the previous one (a sibling), and “^” allows you to climb back up a level to create an element. For the sake of simplicity, let’s start with the first two.

screenshot

As you can see, with the child symbol (just like the child selector in CSS), I was able to place the inner div inside of the outer div. Then I used another child symbol followed by the sibling symbol to place both the h2 and the paragraph on the same level right inside the inner div.

Climbing Up

Now let’s move on and look at moving up the tree. This one is a little more complicated to wrap your mind around but is an awesome new Emmet feature that we didn’t have in Zen Coding. Basically, using the “move up” symbol, we can climb out of a branch that we’ve begun to dive into. Here’s what I mean:

screenshot

As you can see here, we dug into the first paragraph and tossed in an anchor tag, but then needed to climb back up and add another paragraph on the same level as the previous one. The “^” symbol allowed us to accomplish this.

To make this feature even more useful, you can chain these symbols together to climb back multiple levels. For instance, if we added an em element to our previous abbreviation, we’d have to climb up two levels to place our next paragraph on the same level as the first.

screenshot

3. Use Grouping to Simplify Your Structure

Sometimes you’ll find that you’ve dug so deep into a particular branch that it becomes a confusing mess to chain together enough climb up symbols to get what you want. In this case, it might simplify things a bit if you turn to grouping instead. This is accomplished by implementing parentheses around different sections of code.

screenshot

This actually feels more natural and logical than using the climb up symbol, and really we’re accomplishing the same thing. You can see this really start to pay off when you’re outlining a larger portion of your page.

screenshot

4. Insert Text and Attributes

As you’re marking up your page, text and attributes are two things that you might expect that you can’t perform with Emmet. Many users simply outline a document with this tool, then fill in the content gaps after the expansion. This is a great way to work, but if you’re interested, you can insert both text and attributes using the syntax shown below.

screenshot

As I’ve shown above, text is inserted via {curly brackets} and attributes utilize [square brackets]. Keep in mind that anchors actually automatically insert an “href” but the value for it is left empty by default, this technique allows you to fill it. Further, remember that you can use curly brackets to create any attribute that you like, not just the one shown here.

5. Multiple Class Names on a Single Item

This one is super simple, but when I first began using this tool, it wasn’t clear to me how to add multiple class names to a single element. It turns out, all you have to do is type out all the class names in a row separated by periods.

screenshot

6. Multiplication

This is another one of my favorites. You can save yourself tons of typing when inserting multiple elements of the same type. Simply use the following syntax:

screenshot

This works on pretty much anything you need it to, no matter how complicated. Try pairing it up with the grouping feature that we saw before for some interesting results.

screenshot

7. Automatic Numbering

Our seventh and final tip is that you can insert automatically incrementing numbers into your snippets via the dollar sign. This works anywhere: classes, IDs, text, attributes, etc. Here’s an example in action:

screenshot

Notice that, the more dollar signs you use, the more digits the number will have. So in the first instance, I used $, which expanded into 1, 2 and 3. Then in the second instance, I used $$, which expanded into 01, 02 and 03.

Try Them Out!

Now that you know a bunch of seriously amazing tricks to try out with Emmet, it’s time to give them a shot. Hit up our Emmet demo page and try out a few of the abbreviations that we went over above. Here’s a list of each abbreviation in this article in plain text for your copying and pasting convenience.

<!-- Skip The Div #1 -->
div.container

<!-- Skip The Div #2 -->
.container

<!-- Implicit Tag Names -->
.wrap>ul.list>.sites

<!-- Chaining Abbreviations -->
.outer>.inner>h1+p

<!-- Climbing Up #1 -->
.wrap>p>a^p

<!-- Climbing Up #2 -->
.wrap>p>em>a^^p

<!-- Grouping #1 -->
(.one>h1)+(.two>h1)

<!-- Grouping #2 -->
(section>.wrap>h1>p>a)+(section>.wrap>p+p)

<!-- Text & Attributes #1 -->
h1{heading}+p{lorem ipsum}

<!-- Text & Attributes #2 -->
a[href="http://www.apple.com"]{Apple}

<!-- Multiple Class Names -->
.one.two.three

<!-- Multiplication #1 -->
ul>li*3

<!-- Multiplication #2 -->
(section>.wrap)*2

<!-- Automatic Numbering -->
ul>li.item${item $$}*3

Also be sure to hit up the Emmet home page, where you can learn more and try it for yourself right away.

How Do I Expand Abbreviations?

Expansion can be different in each editor and typically requires a plugin. In Sublime Text 2, open Package Manager, search for Emmet, install it, then restart the app. To trigger an expansion, simply hit tab after typing in an abbreviation.

 

source: Design Shack

Defensive HTML and CSS

By | Coding | No Comments

When it comes to rendering on somebody else’s DOM, you can’t naively write HTML and CSS like you might for your own self-contained web application. You’ve got to think carefully about how preexisting CSS and JavaScript code might affect your application.

Before you begin to write any HTML or CSS, you’ll have to make an important decision regarding the look and feel of your application. Do you want your application to look the same everywhere? Or do you want the application to inherit the native look and feel of the page on which it’s hosted? Your answer will have a profound effect on your strategy for rendering your app.

One thing is constant: at some level, you’ll be practicing what we call defensive rendering. By defensive, we mean taking steps to output HTML and CSS that minimize the impact of the parent page on your application. The less you want your widget impacted by the parent page, the more steps you’ll have to take. These steps can be as small as namespacing your HTML and CSS to reduce name conflicts, or overspecifying your CSS rules so they take priority over rules from the parent page. For widgets that want complete immunity from the parent page, it could also mean serving your widget on a completely separate DOM, embedded in an iframe.

We’ll focus on rendering HTML and CSS that live on the same DOM as the publisher’s page. For widgets that aim to offer some level of customization, this can be the most flexible solution for publishers, since the publisher can easily target your elements and style them to their preferences.

Unfortunately, this is also the downside. The publisher could unknowingly have CSS rules and/or JavaScript code that inadvertently target your widget and wreak havoc.

We’ll look at a number of ways to shield your application’s HTML and CSS from the publisher’s code. First, you’ll learn about HTML and CSS namespaces. Then, you’ll learn about CSS specificity, and how the parent page’s styles can override your own.

Finally, you’ll learn techniques for overruling the page’s parent styles, by overspecifying your CSS and abusing the !important keyword. First up, namespaces.

Namespaces

All DOM IDs, classes, data-* attributes, and matching CSS selectors have been prefixed with stork-. The purpose? To reduce the likelihood of those attributes conflicting with the parent page.

Consider the following situation. Your widget has a top-level <div> element that acts as a container. It does this by setting an explicit width and height, effectively bounding the area taken up by your widget. You’ve given this <div> a straightforward class name, container, which matches a style rule in your accompanying CSS:

<div>
...
</div>
<style>
    .container { width: 200px; height: 200px; }
</style>

This might be perfectly appropriate for a regular stay-at-home application, but for a third-party app, it’s a complete no-no. The reason? Such a generic class name has a good chance of already being used by the parent page. If you introduce this style rule, you might override an existing style rule put in place by the publisher and ruin their site layout. Or, on the flip side, their rule might override yours and resize your widget inadvertently.

The solution? Prefixing all of your class names (and other attributes) with an identifier unique to your application—a namespace. In the case of the Stork widget, the previous markup should be amended to look like this:

<div>
    ...
</div>
<style>
    .stork-container { width: 200px; height: 200px }
</style>

The idea is that you namespace your JavaScript code so that you don’t declare global objects that conflict with code running on the parent page. It extends to every piece of HTML you insert into the page: IDs, classes, data-* attributes, form names, and so on.

Namespacing HTML and CSS is a must for any third-party application that renders directly to the publisher’s page. This isn’t just necessary for preventing conflicting CSS rules; it’s also conceivable that the parent page has JavaScript that’s querying the DOM for elements whose identifying properties might match your own. Be rigorous in namespacing everything you put on the DOM.

CSS specificity

It’s important to note that, though helpful, namespacing your HTML and CSS only prevents cases where the publisher is using styles or queries that reference attributes with the same name as yours. Unfortunately, your widget can still conflict with styles defined by the parent page, even if their CSS uses IDs, class names, and attributes that don’t directly reference your elements. This is because some CSS rules are weighed more heavily by the browser, and can take precedence over seemingly unrelated rules you might define. This phenomenon is referred to as CSS specificity, and you’ll need to understand it before you can safely render elements on the publisher’s page.

Let’s go back to the container example from the previous section on namespaces. Suppose the publisher’s HTML has a top-level DIV that wraps all their content, with an ID of page:

<div id="page">
    ... <!-- Publisher content -->
    <div>
        ... <!-- Stork content -->
    </div>
</div>

Additionally, let’s say the page has the following CSS, where the first rule is defined by the publisher, and the second rule, targeting stork-container, is added by your third-party script:

/* Publisher */
#page div {
    background-color: green;
}
/* Camera Stork */
.stork-container {
    background-color: blue;
}

Now, what color will .stork-container have? The answer might shock and appall you: green. In this simple example, the publisher rule (#page div) takes priority over your third-party application’s class rule (.stork-container). This happens because the browser weighs rules containing IDs higher than those that target classes or attributes.

CSS rule priorities

The W3C CSS specification outlines how browsers are meant to prioritize different rule types. Here’s a list of these rule types, ordered from highest priority to lowest:

  1. Inline styles (style=”…”)
  2. IDs
  3. Classes, attributes, and pseudo-classes (:focus, :hover)
  4. Elements (div, span, and so on) and pseudo-elements (:before, :after)

According to this chart, inline styles are weighed above all subsequent rule types: IDs, classes, and elements. This continues logically down the list, with IDs prioritized higher than classes and elements, and so on. There’s one exception to this list: properties tagged with the !important keyword take highest priority. But note that the !important keyword affects a single property within a rule, not the entire rule.

What happens when you have multiple CSS rules of the same weight, each of which could conceivably affect the same element? Let’s take a look at an example:

<div>
    <span class="stork-msg">Eat your vegetables!</span>
</div>
<style>
   .stork-container { background-color: blue; }
   .stork-container span { background-color: red; }
   .stork-container .stork-msg { background-color: yellow; }
</style>

What do you suppose the color of the span is? The answer again might be surprising: yellow. Even though these rules are all primarily class-based, the second rule (.storkcontainer span) is considered more specific than the first rule, and the third rule (.stork-container .stork-msg) more specific than the second. How does this work?

Inline styles are king

In terms of CSS specificity, that is. If you recall from earlier in this chapter, we mentioned that inline styles have the benefit of rarely conflicting with the parent page. Now it’s clear why: they’re prioritized over every other type of regular CSS rule (excluding those with the !important keyword). If you’re writing a particularly simple widget, it might not be a bad idea to use inline styles; you’ll avoid most CSS specificity conflicts.

The browser uses a simple scoring system to determine which rule takes priority. For a given rule, each selector composing that rule is worth a certain value. Those values are summed to create a specificity score. When multiple rules affect the same element, the browser compares each rule’s specificity score, and the rule with the highest score takes priority. In the case of a tie, the rule that was defined last wins. Inline style attributes: 1000; IDs: 100; classes, pseudo-classes and attributes: 10, elements and pseudo-elements: 1.

So, looking back at our previous example, those CSS rules would have been assigned the following scores, with the highest-scoring rule being prioritized by the browser:You’ll quickly notice these aren’t ordinary numbers. A specificity score is actually a tuple of the form (a , b , c , d ), with a being more valuable than b , b being more valuable than c , and so on. That means that a style caused by a single inline style attribute (1, 0, 0, 0) has higher specificity than a rule with one hundred ID selectors (0, 100, 0, 0).

  • .stork-container (0,0,1,0—one class selector)
  • .stork-container span (0,0,1,1—one class selector, one element selector)
  • .stork-container .stork-msg (0,0,2,0—two class selectors)

At this point, you should have a good handle on how CSS specificity works, and why the browser prioritizes some rules over others. You’ll next put this knowledge to use, as we explore some approaches for writing CSS that stands tall in the face of conflicting publisher styles.

Overspecifying CSS

The first and simplest approach to writing CSS that doesn’t conflict with the publisher’s page is to overspecify your rules. This means declaring additional selectors to boost the specificity of your rules, such that when the browser compares your rules against those from the parent page, they’re likely to score higher and be prioritized.

Let’s look at this in practice. Consider this revised example of the Stork widget container, now sporting two container elements, each with a unique ID:

<div id="stork-main">
    <div id="stork-container">
        <h3>Mikon E90 Digital SLR</h3>
        <img src="<a href="http://camerastork.com/img/products/1337-small.png" rel="nofollow">http://camerastork.com/img/products/1337-small.png</a>"/>
        <p>$599</p>
        <p>4.3/5.0 • 176 Reviews</p>
    </div>
</div>

The accompanying CSS for this HTML could then look like this:

#stork-main #stork-container { ... }
#stork-main #stork-container .stork-product { ... }
#stork-main #stork-container .stork-price { ... }

By redundantly specifying both container IDs as parent selectors of all your CSS rules, you’re effectively giving each of your CSS rules a minimum specificity score of (0,2,0,0). Afterward, the publisher’s generic #page rule from earlier will no longer conflict with your widget, because it only uses a single ID . Neither will any purely class- or element-based rules conflict, because those are an entire CSS weight class below ID s. Even though, for selection purposes, it’s completely unnecessary to specify a second ID for your rules, here it works as an effective device for boosting specificity.

Preserve your sanity with a CSS preprocessor

Writing overspecified CSS can be a real drag: you have to constantly rewrite the same IDs over and over again for each one of your CSS rules. You can remedy this by using a CSS preprocessor, which extends the CSS language with additional features like the ability to declare nested hierarchies of rules. For example, using the LESS CSS preprocessor, you could write the previous example like this:

#stork-main {
   #stork-container {
       .stork-product { ... }
       .stork-price { ... }
   }
}

A number of popular CSS preprocessors are available today, all of which have varying feature sets. Among the most popular are LESS, Sass, and Stylus.

On the flip side, this example requires that your widget use top-level containers with IDs, which won’t be practical for widgets that can be rendered multiple times on the same page. Additionally, it’s still not bulletproof: a publisher could follow your lead and overspecify their own CSS rules, resulting in the same problem you had before.

But this is an unlikely scenario, especially since you’ve redundantly specified two IDs in each of the rules. You could alternatively use one, but this will of course be more vulnerable. The reality is that most publishers use sane CSS rules, and overspecifying your rules like this will be compatible with most of them.

Overspecifying CSS doesn’t mix with code quality tools

If you take to overspecifying your CSS like this, you might find an unlikely enemy: tools that evaluate the quality of your CSS code, such as CSS Lint, Google Page Speed, and Yahoo’s YSlow. These tools will indicate that you’re making redundant CSS selectors, and they’ll advise you to remove such selectors to reduce file size and improve browsers’ CSS performance. Unfortunately, these tools aren’t programmed with third-party scripts in mind, and don’t fairly evaluate the usefulness of overspecifying CSS. The benefits of overspecification for third-party applications will outweigh the extra file size and minuscule performance hit.

Abusing !important

If you feel that overspecifying your CSS with extra ID or class selectors doesn’t go far enough, you can break out the nuclear option: the !important keyword. Properties within a CSS rule that sport the !important keyword are prioritized highest of all, even above inline styles. This is because the !important keyword was designed to give browser users a surefire way to override “author” (publisher) styles, in the case of browser plugins or site-specific styles. You can abuse !important by using it on all of your CSS properties, effectively prioritizing them over all other rules.

Here’s how you might use the !important keyword on a single CSS rule:

.stork-price {
    font-size: 11px !important;
    color: #888 !important;
    text-decoration: none !important;
    display: block !important;
}

Since it’s per property, the !important keyword needs to be repeated like this, which can become a drag over a long and complex stylesheet. But, in exchange, you get a rock-solid set of stylesheets that are very unlikely to be reset by the publisher’s page.

It’s still conceivable that the publisher could in turn use !important to target your elements and set their own styles, at which point they’re likely purposely targeting your elements for customization. On one hand, that can be frustrating if you’re trying to maintain a consistent look and feel. But, if you’ve decided to allow publishers to customize your widget, this is probably desired behavior.

One thing should be clear: sharing the DOM with the publisher can make it particularly difficult to render a consistently styled widget. Although you can take steps to overspecify your CSS rules to reduce the likelihood of conflicts, it’s always possible for the publisher to target your elements with their rules, either accidentally or purposely.

But if sharing the DOM with the publisher is what’s causing so much grief, is it possible to render your widget off of the DOM? Why, yes—yes you can.

Summary

For a third-party JavaScript application, injecting HTML and CSS into the publisher’s page requires more care than if you were adding markup to a “safe” environment. You must make sure that when outputting HTML to the page, you aren’t slowing down the page with a blocking operation. You also have to consider that your script might get included multiple times on the same page, and it should render multiple instances gracefully. Additionally, you should choose an optimal method for injecting CSS into the publisher’s page—either by inlining all your styles, appending link elements, or embedding CSS rules in your JavaScript.

But just getting HTML and CSS on the page isn’t enough. You have to recognize that elements you introduce to the DOM can conflict with the parent page. You also must consider how your styles might conflict with existing styles defined by the publisher. You can use a number of techniques for reducing the impact of parent styles on your widget: by overspecifying your CSS rules or presenting your content behind an iframe, whether it’s a src-less iframe or one that contains an external HTML document.

source: Webdesign Ledger