Tag: Frontend

The goal

Have SCSS stylesheets that look as if there written by 1 developer while working in a team.

Is this even an issue to begin with?

Frontend developers tend to be strict on the way they write CSS/JS but that’s not the main reason. Having organized and clean code is key for fast iterations. Everyone wants to be Agile these days.

If all the files look the same it’s easy to read and easy to pick up again in the future should the project require more phases.

How did we do it?

All recent projects at TBSCG have a build process (Grunt) to compile SCSS, JS, HTML, etc. So we simply included a linter task in that process.

We created a rules file to specify what want we wanted to enforce. Things like:

HEX color codes should be in variables. And even better, all in 1 file.

Spaces between brackets and class names.

Break lines between rules.

No !important anywhere 😎

Leading zero ( .5 vs 0.5 )

Order of the properties (did you know ordering the properties generates smaller gziped files than unordered?)

We only add this linter task to the dev build, so it will never crash in production should we commit a file with errors.
However, with the dev task Grunt will stop as we configured this to be errors not warnings.

Alright, I know what you must be thinking. In some cases hacks might be necessary (we all know how pesky CSS can be), there is a special markup to bypass the enforced rules. It should be used in very special cases. Otherwise the linter makes no sense.

Examples

Because code speaks better than me. Here are some examples of what I mean.

The following code fails to comply with the linter rules. Thankfully Atom knows that and highlights the problems even before I run my Grunt task, so I can fix them as I go.

When running the Grunt task (in case your IDE does not warn you). Here’s the output:

SpaceBeforeBrace: Opening curly brace `{` should be preceded by one space
PropertySortOrder: Properties should be ordered bottom, display, position, width, z-index
DuplicateProperty: Property `bottom` already defined on line 4
SpaceBeforeBrace: Opening curly brace `{` should be preceded by one space
DeclarationOrder: Expected item on line 14 to appear before line 12. Rule sets should be ordered as follows: `@extends`, `@includes` without `@content`, properties, `@includes` with `@content`, nested rule sets

Now here’s the code fixed to pass the linter. Looks better, doesn’t it?

Using it in a real project

Everything is great and all but can this be used in a real project? Does it make sense? Is it productive?

I won’t deny there’s a learning curve for those developers who are used to write code without any strict code style. I truly believe this is good in the long run. Once you get used to the rules, you’ll use them as you type.
The IDE is also important, you need to install the proper plugins to detect the linter config file, so it warns you without the need to run Grunt. In our case Grunt is our second line of defense. Your own editor should be the first to let you know.

Here’s the opinion of Artur Spulnik a Web Developer at TBSCG who worked with me on this real experiment:

Thanks to these principles code was much easier to read and maintain. I had to summon all my knowledge about the alphabet to correctly queue all definitions. There was a lot of pain in the beginning with operators order, and those wild spaces (or lack of them). But with practice comes success and I felt boost of productivity. Especially in terms of teamwork.

Have you ever written code this way? If you haven’t, will you give it a try?

It could be worse than the example above, I’ll give you that. We could have even more classes and “polluted” HTML. However, by using the core classes in my example I just had to write a single CSS class!

SCSS using Bootstrap Classes in HTML

I needed a custom margin on some elements, so I created a generic class for it.

.margin-top-1-5 {
margin-top: 1.5rem;
}

Conclusions

The client shouldn’t care about the HTML

That’s our job, we as developers, can find the middle ground where the HTML is readable while keeping the CSS as performant as possible.

From the developer point of view

It’s a hassle for Frontend and Backend developers. If they’re already familiar with the core Bootstrap classes they can create components without any new CSS.

On the other hand, if you only use custom classes you’ll need someone to create all the new component custom classes, add it to the CSS pack and then build the HTML for it.

CSS footprint

It’s obviously heavier to have all those styles for each component. Here’s the result of my testing:

I know it’s a bold statement but let me show you what I’m talking about, you’ll be amazed.

Developers call them Progressive Web App because:

Progressive: It should work for every user, regardless of browser choice (we’ll see about that). The idea should be that all browsers will catch up, eventually.

Responsive: Hello? 2016 is calling. Although it’s a must nowadays some customers still don’t get it.

Connectivity independent: Offline websites? You got it.

App-like: the user will have the same feeling as in a native app.

Safe: HTTPS only.

Discoverable: Search engines will know this are webapps, we’ll make sure of that by using a valid W3C manifest.

Push Notifications: that’s right, this is killer.

Installable: The user will be able to “install” this on their homescreen via a browser UI, they’ll launch it like a native app.

Linkable: just share the webapp URL and you’re done. No more searching inside App stores.

Don’t want to read? Watch this instead

This 30 minutes video will dive into Progressive Web Apps, check it out if you prefer to hear if from Google Developers.

First of all, Add To Home Screen

Chrome has a built-in UI for adding your webapp to the homescreen of your device (in the example below, an Android phone). It’s great because a consistent UI for this action will be more friendly to users.

Running the provided command from my computer terminal to trigger the push notification.

Awesomeness happened. Chrome showed a notification to my Android, even without being open or running.

As you can imagine, we depend on the browser adaption of Service Workers. In Android, for instance, only Chrome, Firefox (44) and Opera have support.
Next time someone tells you Safari or Microsoft Edge are “modern” browsers punch them in the face.

Blame also Apple’s iOS (iPhone), at the time of this writing Chrome for iOS does not have the freedom to use Service Workers. So, it’s the phone operating system that prevents us from moving forward. No surprise there knowing how many millions of dollars Apples makes from its App Store.

Conclusion?

At this point I hope I’ve awaken a feeling of curiosity for progressive web apps. I feel like the web is the future of mobile. Not just me but big names such as Google. Native web apps are a pain in the butt, why would you need to learn other languages and technologies to build for Android, Apple, Windows Phones…?

If you already know how to build websites, the learning curve should be way shorter than learning how to code for iOS, for instance.

Eliminating the friction between the user and the service you provide is key for better engagement. One website to rule them all, no matter in what platform or screen size your user is in. No more getting out of space in your phone due heavy apps.

Before using templates if I had to change an item on the menu component, a class or a tag that was used in all pages, well… I had to do it manually for all pages. Maybe for some cases I could do a “find & replace”. But in any case, still a hassle.
Now I just edit the template file and all the pages are recompiled instantly with the new change.

Variables

We can also set variables:

{% set pageTitle = "Home" -%}

Then use it on our templates as so:

<title>{{ pageTitle }}</title>

I use this mostly for the page meta title. I set the variable before including the _head.html template so that it will inherit the value. It allows me to have just 1 file for the head HTML but at the same time customized for each page.

Loops

A grid view of images? A list of products?

For all those cases we can use a loop. This will allow us to just write the item/component once. The maintenance will be really easy afterwards.
Imagine using the old way and having a component repeated 20 times in the same page.

Folder structure

It can be anything since you’re free customize the jinja grunt task to fit your project.

What does this mean for the Backend Developer?

Nothing. Nada. Nic. You will still have a folder called html for the compiled files.

Just remember, if you need to change the static HTML’s you will have to update the html–source folder and run the grunt task. Otherwise bad things will happen.

Conclusion

Additionally to all this, since we’re splitting up the files we can easily have multiple developers working on HTML’s without stepping in each other toes.
One can work on the _head.html file, while the other on the homepage.html file. Both will be able to commit their code and do changes without having to merge. Pretty sweet.

I believe using this templating engine will boost your productivity while the impact on your workflow will be minimal. I’ve already used it on a real project and it has greatly improved my delivery and bug fixing times.

I use Google Chrome on a daily basis to render my HTML slices and debug any web page, it is my first choice. Why? The Chrome DevTools.

All hail the Chrome DevTools

Chrome’s built-in authoring and debugging tool.

If you’re a developer you already know what I’m talking about. If you’re a power user you might have heard about it or even seen it.

Basically it’s a tool that allows us to do magic inside our browser. We can see the source code, see how long takes to load a page, what scripts is it using… It has a lot of goodies. Honestly, there’s options I’ve barely used or never seen.

I would like to do a quick introduction to some of the tools I use when working on projects to speed up development. Some of this tips can be used even if you’re not a developer. A Delivery or Project Manager can make use of them to do their jobs.

Emulate Mobile or Tablet

On of the things you might want to do is see how a website is displayed on a mobile device. If you don’t have a real device with you, you can use the DevTools Device Mode.

If comes with a set of predefined devices that not only will resize the screen to the device size but will also change the User Agent to actually trick the site into thinking you’re using the real device.

Even more, you can also emulate how a website would load on a 3G or 4G network.

Scalable Vector Graphics (SVG) is an XML-based vector image format for two-dimensional graphics with support for interactivity and animation.

At this point I’m sure you have heard about font icons. You know, these icons everybody uses nowadays for social networks or just about anything a designer can think of.

On our website we use them too, they’re great. Lightweight, easily customizable with CSS and specially retina ready. They will look good on any device.

They have some issues

Font Icons are not all that great. The styling can be tricky in some situations, they depend on styles such as:

font-size, line-height, vertical-align, letter-spacing, word-spacing

Also, in some cases they might look different depending on the client browser. As the font icons are treated as text.

Let’s kick it up a notch

On the scale of cool-web-tricks regarding graphics we have the following:

Images: stay away from me.

Font Icons: we’ve had a good time.

SVG Icons: hello, gorgeous!

Some font icon packs already include an SVG version of the font that will be served to compatible browsers. That’s not what I want to introduce today though, I’d like to show you a more manual control over those SVG’s. Simply throwing a bunch of fonts into the project is not how the cool kids do it.

Also, the compression by gzipping SVG’s is better than compressing fonts. However, SVG’s tend to be bigger. You’ll have to take decisions when using large set of icons, it will depend on the project and requirements.

Hang on to something, here comes your first SVG

Because I don’t want to go easy on you we’ll start with a big fat SVG:

Ok now, don’t be scared, it won’t bite you. This code could be inline in the HTML or on a separate .svg file.

This SVG was probably generated with a desktop software, Illustrator or something similar. Although, if you need how they work you could code basic forms by hand.

If you take a deeper look you’ll see each path has a class. We’ll use them to style it like so:

.first {
fill: green;
}
.second{
fill: red;
}
.third {
fill: blue;
}

With SVG you can even use stroke-width and stroke to style the border of each element:

stroke: #c0392b;
stroke-width: 2px;

Beautiful.

Final thoughts

There is no SVG support in IE8 and in some old Android browsers. If needed, detect the browser and create a fallback.
In the other hand, if you need old browsers and you don’t actually need the extra customization SVG has to offer, stick with font icons. Once your clients drop IE8 from their requirements, you can do the upgrade.

Ok, here’s the situation: you’ve started your project, currently your team has frontend developers and backend developers. Everyone is happy and doing their parts.

As frontend developer I can tell you that the fastest way to slice or prototype pages is working with plain HTML files. It allows you to work with your (S)CSS and JavaScript files without any issues of caching, server-side compiling, etc. It just works.

What happens when the pages are ready for implementation?

You guessed it, it goes to the hands of the backend developers who will do their magic: create the components for choose your favourite CMS here.
At this point we’re still happy, everything is working just fine and the project will be delivered on time.

First iteration

A couple of days have passed and some JIRA tickets have been raised: we need to fix something in the frontend.

No problem, the frontend developer will open up the HTML files and do the proper edits.

Iteration two hundred seventy six

At some point between revision 1 and revision 276 someone updated the backend CMS component and not the HTML static file. Probably the change was simple enough, there was no need to involve any frontend dev.
That is actually fine! It’s way cheaper, project-wise, and faster to develop.

Now, be careful, that decision might cause a lot of trouble in the future, when new major features will need to be added. An out of date slices will force us to download source files from production. We all know those files can be messy, with random ID’s everywhere, extra empty divs, inline styles, uncommented code…

So, what’ the proper way of applying frontend changes?

I would add that in case of a JavaScript change, even if we’re using Grunt or similaryou might be able to do the change yourself. The issue might be that not everybody has it installed locally. Although I would certainly recommend it 😉

Also, if the project has enough budget to have a frontend developer on board, the above workflow is useless. Just send everything to the frontend dev.

Conclusion

Try finding balance!

This best practices should not be a burden, if you get used to it I think you’ll get real benefits. If someone is capable of changing a component’s markup, is also capable of editing plain HTML files.

You should always keep your static HTML files up to date. Not with content changes but markup. I’m not saying it’s easy or cheap but it’s the right way to iterate. Not all projects will have the budget or client will to maintain this code standards. We, as professional, need to advice and convince our clients this is mandatory. In the end, it will probably save them money.

I hope now you have better insight of how you can be more productive and have a better future-proof code in your projects.

I recently performed an audit for a client of their AEM development and deployment. Part of that audit covered their AEM page renderers and components. They had started their development with AEM 6 which allowed them to use the new Sightly interpretor for their components. The following is some items I picked up that are generic enough to share.

Sightly != JSP

It may sound obvious, but Sightly is not JSP. This means a S(l)ightly different mindset is required when developing these files. This mostly revolves around the use of control structures that are such a definite part of Java in JSP, but are more elegant in Sightly.

data-sly-unwrap as control structures

In this audit I repeatedly saw the use of an extra <div> just to wrap a conditional. This is basically taking the logic from a JSP script and converting it to Sightly. Imagine the following code in Sightly:

Pass WCMUse Objects to templates

The client was following best practice by using templates for their repetitive code, but in some cases I noticed they were passing a WCMUse class name through to the template so that it could be instantiated with a data-sly-use. However in all cases I could find this WCMUse class was already instantiated in the Sightly file calling the template – resulting in two instantiations of the object.

Working on a frontend project you probably have dealt with CSS and JavaScript files. How do you handle those? Do you minimize them? Do you combine them?

I’m sure you’re aware of the benefits of minifying assets. You can save a lot of Kb’s from your CSS and JavaScript files. Nowadays performance matters, it really does. With more and more mobile users every day, your site should be lightweight.

How do we minify and/or combine assets before moving your site to production?

First of all, here’s a thought about folder structure for your project:

I’d recommend using a folder structure similar to this one. Grunt does not force you to any specific folder structure, you’ll have the freedom to set the output folders on each task.

You’ll be doing all your work in the source folder. Your files will be commented, uncompressed and separated into components. It’s a good practice to breakdown your CSS into different files, it will help you and your team keep the code organized. Great for collaboration.

What’s with the dist folder?

The dist folder will eventually have all the processed files, perhaps a single CSS file (merged from 10 separate CSS components).

Bear in mind though:

Combining all CSS/JavaScript into 1 file is not a synonym for optimal performance.

NOTE: the concat task is part of the Concat Grunt Plugin. You must install it and configure it before using the concat task.

You’ll set it to this new dist folder so all your processed, compressed code will be located there (in the case above we’re merging all our files into one and saving it as project-main.css ).
When it comes to production we don’t want to upload our source CSS/JS files.

Watch for file changes.

That’s probably my favourite feature of all. By using the Grunt Watch Plugin you can simply run the grunt task on your terminal and watch over the changed files (please notice you’ll need some extra configuration in your Grunt config file before actually making this work, refer to the plugin’s site):

grunt

This will keep an open task in your terminal that will wait for any file change. Every Time you edit a SCSS or JavaScript file, Grunt will re-run. What’s great is that it will not run the whole thing.
Say all tasks (merge, compress, minify, move…) take up to 30 seconds. With the grunt watch it will just compile the affected files. Meaning it might only take 5 seconds.

I don’t like the Grunt logo, are there any alternatives?

There’s plenty of blog posts out there breaking down a comparison side by side. It’s your job to decide what’s best for you and your team.

From what I’ve read both are more than capable of delivering your needs.

Final thoughts

I know what you think, do I have to learn yet another tool?

I felt the same way the first time I read about Grunt.js At that time I was using a desktop application for compiling SASS, running JSLint, minifying… and that’s great, until there’s two developers working on the same project.

It can get complicated, some Grunt configuration files can easily have 300 lines. However, once you start reading and looking into it you’ll see it’s less painful than how it looks.

In my previous article I was trying to convince you to start coding your CSS using a CSS Preprocessor (SASS). With Grunt you can process all that files, merge them and move them to the dist folder without even thinking about it.

By the end of the article you’ll be asking yourself: “What could’ve I done with all the time I’ve wasted writing CSS?”

What’s a CSS Preprocessor anyway?

A CSS Preprocessor extends the CSS language by adding features that will make your life so much easier. The code will be more maintainable, easier to read and faster to type (well, not faster but you’ll certainly type less).

If you do a quick Google search for “CSS Preprocessor” you’ll probably come across: Sass/SCSS, LESS or Stylus.
All of them, more or less, serve the same purpose with some small variations. You’ll have to choose one, lucky for you there’s no right or wrong choice.

All the code you write with this new syntax will have to be compiled into normal CSS. What great about it is that we can set minification and compression with the same process (we all know how #perfmatters).

How to have fun while writing CSS

At TBSCG we use Sass when we need to bring out the big guns. With that said, CSS Preprocessors aren’t usually used when you need to do a small change in an existing project using regular CSS. Once again it’s up to you, if you think you’re going to edit this on a daily basis perhaps you should consider creating a .scss file. One cool thing is that SCSS syntax is superset of CSS so you can actually paste regular CSS into a SCSS file and compile it. It won’t be any different but then you could use SCSS syntax for the new pieces of code.

The wait is over, what are those features I’ve been talking about?

Variables

We can create our own variables. Yes, like in a “normal” programming language. We usually create a specific file where we write all our variables so we can easily keep a track of them.

@import, let’s keep it clean

I’ve mentioned different files, it’s a good practice to separate your components SCSS into different files. It will be easier to maintain and it’s great for collaboration. Don’t worry, all those files will only generate one CSS compiled file.

You could have your main.scss with this:

@import "components/header";

Which will be fed from components/header.scss

Nesting

Using the example from the beginning of the article we could’ve written it like this:

Nesting allows us to save a lot of writing. You have to be carefull though, with this feature it’s easy to overdo creating too many selectors and children. Sometimes a root level class will be more than enough.

Functions and Mixins

So yes, we can create our own functions. Like you would expect, this functions accept parameters and will help you reuse code and write less.

They can do anything you want, i.e. change string to int:

@function parseInt($n) {
@return $n / ($n * 0 + 1);
}

We can call functions like normal function, ie.:

.class {
line-height: parseInt(3.5px);
}

Which once compiled will look like:

.class { line-height: 3.5; }

There are also some “special” functions called mixins, we can use them with the @include directive.

There’s even more

Each language comes with a long list of core functions such as darken() or lighten(), with this two functions we can change the colors using percentatges:

.class{
color: darken($main-color, 20%);
}

This is great to create themes from two or three base colors. Designers get onboard!

If the core functions aren’t enough for you and you need more power, check out Compass. I’ll just quote the description:

Compass is an open-source CSS authoring framework which uses the Sass stylesheet language to make writing stylesheets powerful and easy.

My recommendation would be to first to get a sense of Sass and then take a look at Compass.

I’m sold, how do I compile this things?

If you’re friends with the command line it’s probably the fastest way to get you up and running. If you prefer a GUI there’s also Windows and Mac clients to deal with this files. Check out each language site for their How to Install guides.

Final thoughts

At this point I hope you’re convinced of the power of the CSS-Preprocessors. Like anything in the dev world you’ll have to learn it first, there’s no way around it. As you have already seen it’s not hard and the benefits you get from it are great.
In the end this tools help us be more efficient with our work and allow us to optimize our time.