Why consistency will always beat motivation

One of the beautiful things about being a developer is that many of us actually have the opportunity to take an activity we enjoy, and make it our job. Many developers are happy to do some extra work or learn something when they're at home or in the weekend just because they are so eager to learn and play. While this is pretty awesome, it won't last forever. You won't be motivated to learn every single day. Especially once you start doing development as a full-time job.

I experience this as well, sometimes I have a couple of days or even weeks where my motivation is through the roof. I'll get tons of work done and the days just fly by. On other days I just can't seem to get started, everything is distracting and the motivation just doesn't seem to be there. When I look at some of the more senior developers I know, it seems that they have moved past this phase. They always seem to be motivated and sometimes they just seem extra motivated. They just seem to have no shortage of the good stuff! How do they do this?

Is it worth chasing motivation?

If you think about it, motivation isn't worth much. It's just not there all the time and you can't rely on it being there when you need it most. When I was looking for ways to improve motivation I came across posts like this, telling me that I should get disciplined. Some went even further and said that motivation just isn't worth your time.

Usually, being demotivated is caused by something. For example, you might be tired, eaten poorly, have something else on your mind, or you might struggle with figuring out what it is you should be doing right now. Without clear priorities, our brains absolutely love to zone out, slack off, and leave us procrastinating and wasting time. You can't motivate youself out of a situation like this.

You need a system that you can apply consistently to help you move forward.

And usually, once you get yourself going again, motivation will come back and you're all set up for another productive day.

Turning motivation into discipline

If you want to be more disciplined you'll sometimes have to be pretty tough on yourself. There's rarely a valid excuse to not do what you're supposed to do. So instead of postponing things until you feel motivated, just get started. Of course, this means that you need to have a to do list. Or some other system in place that helps you determine what it is that you need to be doing right now.

You can do this by taking 15-20 minutes at the start of your day or week to figure out what it is that you're going to build, what code are you going to write. Figure out what sub tasks there are and split them up in blocks that will take about 30-60 minutes to complete. If you do this, you will have a great structured overview of what you're going to do. You'll know how busy you are for the day or week and you'll be able to plan accordingly.

You can then use a pomodoro timer or something similar to help you focus for 25 minutes at a time.

After a timer completes, it's time to take a quick break. And try to make it an actual break, get up and grab a drink. If there's email or anything similar that requires your attention, take a peek. Reply if needed or add replying to your to-do list. Make it a part of a new 25 minute timer if the email requires you to figure something out in-depth.

Otherwise, use the break or extend the break a little (but not too much, 10 minutes should be the maximum). In the beginning you might feel like you're restricting yourself because just as you're in the zone you have to get up. And when you're not feeling ready yet, it's time to start back up.

That's fine. In fact, that's the point. You are training yourself to have a consistent and disciplined workflow.

Once you've established a pace and rythm for yourself it's suddenly not distracting at all. Following your system means that you don't spend mental capacity on figuring our what's next. You don't burn through all your energy in a few hours because you never took breaks. You're never spending "just 5 more minutes" on social media. You have a system in place, and that system guides you. It helps you get things done.

The benefits are real

When I look at more senior developers I notice that many of them have a workflow similar to this. They take multiple short breaks throughout the day and between those breaks they tend to be very focused on the tasks they have to complete. They don't have Slack or Teams open all the time and they work on a single thing at a time. And they are consistent about that. Everyday they seem to be able to flick the switch and go into work mode. Of course they still have more and less motivated days, but they know how to get themselves back into work mode.

So let's get out there and become consistently more disciplined!

Expand your learning with my books

Practical Swift Concurrency header image

Learn everything you need to know about Swift Concurrency and how you can use it in your projects with Practical Swift Concurrency. It contains:

  • Eleven chapters worth of content.
  • Sample projects that use the code shown in the chapters.
  • Free updates for future iOS versions.

The book is available as a digital download for just $39.99!

Learn more

Using Flexbox in the real world

The Flexbox module for css was built with the intent to make a more robust, less hacky way to layout elements on pages. When you're building a webpage you often don't know how high or wide every element could or should be. This can cause problems in certain layouts which lead to ugly hacks. Flexbox solves this widespread layout issue. The module has been in development for quite some time and the W3C gave the spec a "last call working draft" status back in september of 2014. The browser support for this module is very good if you don't have to support IE9 so you can safely use it. In this post I will provide a few code examples to show you how you can use Flexbox in some everyday situations.

Creating a filmstrip

Have you ever created a horizontally scrolling filmstrip kind of module? You know the size of the each element in the strip and the size of the containing element but the size of the inner element, the filmstrip itself is unknown. This would normally result in a layout like this and you would have to use Javascript or hardcode the size of the inner element to make this work.

So what would happen if you used Flexbox for this? Well, Flexbox allows an element to grow, not only on the y axis like an element normally does, but also on the x axis. It's one of the reasons Flexbox is really cool. Let's try this.

It's pretty neat, isn't it? Between the first and second example there's only three lines of code that are different. Okay, actually there's a little more but I'm not counting in the vendor prefixes because you don't have to write those if you use an autoprefixer. The first difference is that we give overflow-x: scroll; to the filmstrip container, that's just to make the contents scroll. The second step is to set display: flex; on the inner element. If you did only these two things, the items inside of the inner element will shrink to fit inside of their container. You don't want this so the last thing you do is add flex-shrink: 0; to the filmstip items. The shrink property has a value of 0(false) or 1(true). There's also a flex-grow  property, it's the same as the shrink property but it determines whether an element will grow or not.

Vertical centering

Ever since I started writing css this has been a problem. How do you center an element, with or without a known height, in a container that is or isn't flexible? No matter how you look at it, vertical centering is annoying. I've used hacks that would absolutely position the centered element at 50% from the top and then I would use a negative top margin to push the element towards the center. Another method is to use translating which is slightly cleaner but you still have to use position absolute and a top offset of 50%. You could display your stuff as if it's a table and then vertically center content which works well but it just doesn't feel right. It starts to feel plain wrong once you've tried to do this with Flexbox.

So in this example I've set up a container and inside of that container is an image. Flexbox is used to center the image both vertically and horizontally inside of it's containing element. The property that is used for vertical centering is align-items . The property that is centering horizontally in this example is justify-content . In my opinion, this is the best way to vertically align items I've seen.

Fitting things into a container

The filmstrip example gave this one away already but Flexbox can be used to fit an unknown number of items into a container. This is really nice if you have a couple of images but you can't really be sure of how many. You could optimize for a certain number, let's say four in the case of this example. And then for the edge cases where you have five images or more, you have Flexbox to make the images smaller so everything will still fit nicely into the containing element. Let's check it out.

All we had to do to achieve this is add display: flex; to the containing element. In the first example we saw that, by default, children of an element with display: flex; will shrink to fit inside of that container.

Conclusions and further resources

In this post I showed you three examples of what you can achieve with Flexbox and how you can do that. Note that we just used Flexbox for three small things and that I didn't mention Flexbox as a method of laying out your entire page. The reason for this is that Flexbox is not intended for that. There is a spec on the way for laying out your entire page and it's called grid.

If you're looking for a good overview of how Flexbox works I recommend that you visit this cheatsheet on css-tricks.com. This cheatsheet provides a lot of information on how you can use Flexbox and what properties it has. Lastly, if you're looking for more examples of what problems you can solve with Flexbox check out this "solved by Flexbox" page.

Service workers are awesome

In the war between native and web apps there's a few aspects that make a native app superior to a web app. Among these are features like push notifications and offline caching. A native app, once installed, is capable of providing the user with a cache of older content (possibly updated in the background) while it's fetching new, fresh content. This is a great way to avoid loading times for content and it's something that browser vendors tried to solve with cache manifests and AppCache. Everybody who has tried to implement offline caching for their webpages will know that the AppCache manifest files are a nightmare to maintain and that they're pretty mysterious about how and when they store things. And so the gap between native and web remained unchanged.

In comes the service worker

The service worker aims to solve all of our issues with this native vs. web gap. The service worker will allow us to have a very granular controlled cache, which is great. It will also allow us to send push notifications, receive background updates and at the end of this talk Jake Archibald mentions that the Chrome team is even working on providing stuff like geofencing through the service worker API. This leads me to think that the service worker just might become the glue between the browser and the native platform that we might need to close the gap once and for all.

If you watch the talk by Jake Archibald you'll see that the service worker can help a great deal with speeding up page loads. You'll be able to serve cached content to your users first and then add new content later on. You're able to control the caching of images that aren't even on your own servers. And more importantly, this method of caching is superior to browser caching because it will allow for true offline access and you can control the cache yourself. This means that the browser won't just delete your cached data whenever it feels the need to do so.

How the service worker works

When you want to use a service worker you have to install it first. You can do this by calling the register function on navigator.serviceWorker . This will attempt to install the service worker for your page. This is usually the moment where you'll want to cache some static assets. If this succeeds the service worker is installed. If this fails the service worker will attempt another install the next time the page is loaded, your page won't be messed up if the installation fails.

Once the service worker is installed you can tap into network requests and respond with cached resources before the browser goes to the network. For example, the browser wants to request /static/style.css . The service worker will be notified through the fetch event and you can either respond with a cached resource or allow the browser to go out and fetch the resource.

HTTPS only!!

Because the server worker is such a powerful API it will only be available through HTTPS when you use it in production. When you're on localhost HTTP will do but otherwise you are required to use HTTPS. This is to prevents man-in-the-middle attacks. Also, when you're developing locally you can't use the file:// protocol, you will have to set up a local webserver. If you're struggling with that, I wrote this post that illustrated three ways to quickly set up an HTTP server on your local machine. When you want to publish a demo you can use github pages, these are server over HTTPS by default so service workers will work there.

A basic server worker example

Browser support

Before I start with the example I want to mention that currently Chrome is the only browser that supports service workers. I believe Firefox is working hard to make an implementation happen as well and the other vendors are vague about supporting the service worker for now. This page has a good overview of how far the completion of service workers is.

The example

The best way to illustrate the powers of the service worker probably is to set up a quick demo. We're going to create a page that has ten pretty huge pictures on it, these pictures will be loaded from several resources because I just typed 'space' in to Google and picked a bunch of images there that I wanted to include on a webpage.

When I load this page without a service worker all the images will be fetched from the server, which can be pretty slow considering that we're using giant space images. Let's speeds things up. First create an app.js  file and include that in your page html right before the body tag closes. In that file you'll need the following script:

navigator.serviceWorker.register('worker.js')
    .then(function(){
        console.log("success!");
    },
    function(){
        console.log("failure..");
    });

This code snipper registers a service worker for our website. The register function returns a promise and when it gets resolved we just log the words 'success' for now. On error we'll log failure. Now let's set up the service worker.

// You will need this polyfill, at least on Chrome 41 and older.
importScripts('serviceworker-cache-polyfill.js');

var files_to_cache = [
    // an array of file locations we want to cache
];

this.addEventListener('install', function(evt){
    evt.waitUntil(
        caches.open("SPACE_CACHE")
            .then(function(cache){
                console.log("cache opened");
                return cache.addAll(files_to_cache);
            })
        );
    });

The code above creates a new service worker that adds a list of files to the "SPACE_CACHE" . The install eventHandler will wait for this operation to complete before it returns a success status, so if this fails the installation will fail as well.

Now let's write the fetch handler so we can respond with our freshly cached resources.

this.addEventListener('fetch', function(evt){
    evt.respondWith(
        caches.open("SPACE_CACHE").then(function(cache){
            return cache.match(evt.request).then(function (response) {
                return response || fetch(event.request.clone());
            });
        })
    );
});

This handler will take a request and match it against the SPACE_CACHE. When it finds a valid response, it will respond with it. Otherwise we will use the fetch API that is available in service workers to load the request and we respond with that. This example is pretty straightforward and probably a lot more simple than what you might use in the real world.

Debugging

Debugging service workers is far from ideal, but it's doable. In Chrome you can load chrome://serviceworker-internals/ or chrome://inspect/#service-workers to gain some insights on what is going on with your service workers. However, the Chrome team can still improve a lot when it comes to debugging service workers. When they fail to install properly because you're not using the cache polyfill for instance, the worker will return a successful installation after which the worker will be terminated without any error messages. This is very confusing and caused me quite a headache when I was first trying service workers.

Moving further with service workers

If you think service workers are interesting I suggest that you check out some examples and posts online. Jake Archibald wrote the <a href="http://jakearchibald.com/2014/offline-cookbook/" target="_blank">offline cookbook</a>. There's many information on service workers in there. You can also check out his <a href="https://github.com/jakearchibald/simple-serviceworker-tutorial" target="_blank">simple-serviceworker-tutorial</a> on Github, I learned a lot from that.

In the near future the Chrome team will be adding things like push notifications and geofencing to service workers so I think it's worth the effort to have a look at them right now because that will really put you in the lead when service workers hit the mainstream of developers and projects.

If you feel like I made some terrible mistakes in my overview of service workers or if you have something to tell me about them, please go ahead and hit me up on Twitter.

The source code for this blog post can be found on Github.

Filling in the blanks with calc()

One of the things in css3 that I don't see used very often is the calc() function. Even though this function might not be useful in every scenario it certainly has it's own use cases. In this post I'll try to outline a few of these use cases for you. First, let's start with a quick introduction to the calc() function.

What is calc()?

Calc()  is a function that was added to css3. It allows you to perform calculations on a certain property value, for example the width, font-size or even the margins of an element can be calc()-ed. The syntax for it is quite simple:

.my-class {
    width: calc(100% - 3em);
}

This code snippet sets the width of an element to 100% minus 3em. What's interesting about this is that we're combining both percentages and em values. So you can be partially fluid and partially fixed in your layout. Calc is very powerful and will perform this calculation whenever the element is being layed-out on the screen, making it incredibly flexible. An important thing to notice here is that there are spaces around the minus operator. These spaces are required.

Using calc for gutters

When building your layout you will often want to have a certain gutter in it. For instance, you could want a gutter that is exactly .75em all the time between two elements. For these cases calc is a perfect fit. Here's an example of that.

In the embedded codepen you'll see that we used only a small amount of css to accomplish this layout. A quick look at the css:

.item {
    height: 50px; 
    float: left; 
} 

.item-1 {
    width: 25%;
    background-color: #c0ff3e; 
} 

.item-2 { 
    width: calc(75% - .75em); 
    margin-left: .75em; 
    background-color: #0ff1ce;
}

The nice part about this is that a use can adjust their font-size and the layout will adapt to that because we've used ems. The calc()  function will make sure that our page will still look pretty. If you take this approach to the next level I'm pretty sure it should be possible to use calc()  in a very advanced and flexible grid system.

Calc to fill up the page

There are times where you might want to make an element take up all the width minus some known portion of the page. This becomes interesting in the case of a sidebar with a known width and content that should make up the rest of the page. Let's jump straight in with an example, shall we?

If we ignore all the kitten cuteness that Placekitten.com is providing this example with we're left with this piece of relevant css.

.item-1 {
    width: 250px;
}

.item-2 {
    width: calc(100% - 250px - .75em);
    margin-left: .75em;
}

What this demonstrates is that it suddenly becomes easy to have a partially fixed and partially flexible layout and that calc is very powerful because you can mix all kind of values. Pixels, ems, percentages, calc()  will calculate them for you. It's pretty cool actually.

How about browser support?

I'm glad you asked, browser support is more than decent for the calc feature. All new browsers have implemented it and they have done so for quite some time. Even IE has had support for some time, they only didn't implement multiplying and dividing until IE10. For an up to date list of support you can refer to caniuse.com.

Conclusion

In this post you've learned what the calc()  function is in css3 and I've showed you two real word examples of when you might want to use calc()  in your own projects. Browser support is good so there's nothing stopping you from sprinkling some calculations in to your css. If you have questions, suggestions or feedback you can always send me a Tweet.

Some tips for new front-end developers

You've decided you want to get into front-end development and you've managed to learn a few things. The time has come for you to get some working experience and start growing your career in a beautiful field. I was in that position not so long ago and I noticed that actually having a job and working is a lot different than writing code from the safety of your own environment. So how do you present yourself in a professional way? How do you make sure that you learn as much as you can? Today I want to share some of the things I have learned about this.

Take yourself seriously

But don't be cocky. It's good to show to other people that you're serious about development. It will make sure that they don't just steamroll right over you. It will show that you have passion and aren't just there to put in a couple of hours and then go home aftwerwards. The things you say and do matter and it's okay to make sure that people know. However, at the same time you should be aware that you're just starting out. You're a junior developer and you're in the position to learn. Which brings me to my next point.

Ask questions

When you're trying to proof yourself it's easy to isolate yourself and work really hard. When your get assigned a task you're probably going to want to solve it on your own. It makes sense, you're trying to make a name for yourself and you're trying to be taken seriously. How will your colleagues be able to do that if you can't even be trusted with doing a small, simple task on your own? So you try to keep everything to yourself. Even though this mindset makes a lot of sense I want to advice you to ask questions. A lot of them. Don't just ask about the tasks you're trying to complete but also ask why certain things work the way they do. Ask what motivated a certain technology or design choice in your code base. Even ask you colleagues for their opinions on work related topics. You can learn a lot from them and it will prove to them that you care enough about your job to ask somebody for help with finding the best solutions.

Take responsibility for the code you work with

Now that you're part of a team of developers, you're sharing in the responsibility over a code base. When I was listening to Ben Orenstein's podcast a few days ago he mentioned something he noticed in interviews which really stuck with me. He said that when he asked people he interviewed why a certain piece of code worked the way it did many candidates would come up with a variety of excuses why they didn't know or care about how the code worked. What these excuses usually came down to was that somebody else wrote that piece of code and it wasn't 100% relevant to the task they were trying to do. So they would just assume that the person who wrote the code knew what they were doing and they didn't feel responsible for the code, so they wouldn't touch it.

When I thought about that I figured that I take code written by my colleagues for granted a lot of the time. Event though they often double check my code to see what it does and how it can be improved. They don't do that because they don't trust me, they do that because they feel responsible for the code I write because we all share a code base. So when you touch a piece of code somebody else wrote and you're not sure how it works you should ask somebody. If you do this it will show that you actually care about the bigger picture and that you're taking responsibility for the code that you're working with. And that is a good thing.

Don't pretend you know everything

When I was doing my first internship I though I actually knew a lot. Whenever my boss would come up with a project I would have a solution immediately. I think I kept that up for about a few months until I realized that in fact I didn't really know anything. I knew the very basics of Actionscript and I knew how to create simple things with Adobe Flash and that was it. I wasn't a good programmer, I just didn't know what I didn't know. So I want to advice you to be humble, be aware that you probably don't know half of what you think you know. You don't have the experience to know what works and what doesn't work. And nobody is going to blame you for that. It's okay to say that you're not sure about something, it's also okay to just say that you don't have a clue about how you should approach something. And again, it's okay to ask questions.

If anything, your colleagues and your boss will appreciate the fact that you ask them for help, it gives them a sense of comfort knowing that you're not just doing whatever. Many good developers also seem to enjoy the act of teaching, sharing their knowledge with others. So actually by not pretending you know it all you're learning more, making sure you don't do anything weird and you're providing others with the opportunity to share knowledge.

Take the time to read and learn

If you pick up a book on development every once in a while it will give you a much better understanding of the topic you're reading about. Even though the modern world allows you to find almost anything online I have found that books are a great way to take a more casual approach at learning. I feel like reading a book speaks to a whole different mindset for me and I seem to be able to focus a lot better and longer when I'm reading a book. Also, some subjects require the repetition and explanation that a book can give you.

This also applies to learning a new tool or framework. It's okay to sit down for an hour or two so you can read about it before you start working with it. I have found that doing this will provide a sense of context and it can really help with exploring the feature of the given framework. You'll also be able to gain a much deeper understanding of what goes on because sometimes the framework documentation will go in to why they made certain choices. While these choices may seem insignificant at first sight they might provide you with some context when you're actually working with the framework. Which can help you a lot in the long run.

Conclusions

When you're just starting out as a developer it's really easy to overlook all the things you don't know. When I was just starting out I worked with some people who kept emphasizing that some things were easy but I never knew why. I never asked. And if there's something I've noticed, it's that asking is key to becoming a better developer. And it doesn't stop there, you also have to listen. Listening is a great way to learn. Opinions of more experienced people aren't based on the latest and greatest, they're based on what works and what doesn't. They tend to have experience with a lot of things and also, they tend to admit when they aren't sure. So if somebody with tons of experience tells you something, assume that they know what they're talking about. And if you have doubts, ask them. They will most likely be happy to explain to you what they think and why. They will probably even be excited about hearing what you have to say as well. So I guess this whole post comes down to a few things. Be confident, be eager, ask questions and don't fake it.

Death by papercut (why small optimizations matter)

It's not easy to write good code. It's also not easy to optimize code to be as fast as possible. Often times I have found myself refactoring a piece of code multiple times because I could make the code easier to read or perform faster. Sometimes I've achieved both. But when a project would grow larger and larger things would still feel a little slow after a while. For instance, changing something from doing four API calls to six wouldn't matter that much, right? I mean, each call only takes about 10ms and everything is very optimized!

This is death by papercut

In the example I mentioned above, doing two API calls, 10ms each, isn't a very big deal in itself. What is a big deal though, is the fact that we're doing four other calls as well. So that means that we went from 40ms in API calls to 60ms. that's a 50% increase. And then there's also the overhead of possibly extracting the data you want to send to the API from the DOM and also parsing the API's response on the client will take extra time. Slowly all these milliseconds add up. On their own every part of the application is pretty fast, but when put together it becomes slower and slower.

I'm not sure where I heard this first but I think it's a great one. All these not-so-slow things stacking up and then becoming slow is like dying from papercuts. Each cut on it's own isn't a big deal, but if you do enough of them it will become a big deal and eventually you die a slow and painful death. The same is true in web development, and any other development field for that matter.

So if we should avoid dying by a papercut, and papercuts on their own don't really do damage, how should we do that? Every block of code we write will cost us a very tiny bit of speed, that's inevitable. And we can't just stop writing code in order to keep everything fast, that's not an option.

Staying alive

The death by papercut scenario is a difficult one to avoid, but it's also quite simple at the same time. If you take a good hard look at the code you write you can probably identify small bits of code that execute but don't actually do much. Maybe you can optimize that? Or maybe you're doing two API calls straight after each other. One to fetch a list and a second one to fetch the first item on that list. If this is a very common pattern in your application, consider adding the first item in that initial API response. The win won't be huge, but imagine finding just 4 more of these situations. You may have just won about 50ms of loading time by just optimizing the obvious things in your API.

Recently I came across an instance in my own code where I wanted to do a status check for an X amount of items. Most of the items would keep the default status and I used an API to check all statuses. The API would check all of the items and it would return the 'new' status for each item. It was pointed out to me that the amount of data I sent to the API was more than I would strictly need to identify the items. Also, I was told that returning items that won't change is a waste of bandwidth, especially because most items wouldn't have to change their status.

This might sound like 2 very, very small changes were made:

  • Send a little less data to the API
  • Get a little less data back from the API

As small as these changes may seem, they actually are quite large. First of all, sending half of an already small request is still a 50% cut in data transfer. Also, returning less items isn't just a bandwidth win. It's also a couple less items to loop over in my javascript and a couple less DOM updates. So this case save me a bunch of papercuts that weren't really harming the project directly, but they could harm the project when it grows bigger and bigger and more of these small oversights stay inside of the application, becoming harder and harder to find.

Call it over optimizing or call it good programming

One might argue that what I just described is over optimization, which is considered bad practice because it costs quite some effort and yields only little wins. In this case, because the functionality was still being built it was easy to see one of these small optimizations. And the right time to do a small optimization is, I guess, as soon as you notice the possibility to do that optimization.

I haven't really thought of code in this mindset often, but I really feel like I should. It keeps me on top of my code and I should be able to write more optimized code right from the start. Especially when it comes to data fetching from an API or from a database, I think a very careful approach might be a good thing. Let's not send a request to the server for every little thing. And let's not run to the database for every little thing all the time, that's what caching is for. The sooner you optimize for these small things, the easier it is and the less trouble it will cause you later on.

Three simple ways to start a local webserver

When you first start out with web development you're probably opening html files right in your browser. You're probably using relative urls like /styles/style.css  and this is working fine for you. Right up until you're trying to load some files from a remote location and nothing really works anymore. You ask questions online and people tell you "oh just launch a local webserver and use it to access your files". Yeah, easier said that done, right? In this post I will explain three ways to quickly and simply start a local webserver. I'm going to assume you're either using OS X or a version of Linux for this tutorial.

Python

When you're using a Unix based system like Linux or OS X your machine should already have Python installed. Python comes with the ability to start a webserver for you, all you need to know is where your website files are and how to navigate to the in the command line.

Open up your command line and navigate to your website folder. For example: cd ~/Projects/my-website . Now that we are in the website's main folder we can launch the http server:

python -m SimpleHTTPServer

That's it, you should see some output in your terminal like:

Serving HTTP on 0.0.0.0 port 8000

You can now access your website on http://localhost:8000 and loading external files will work just fine. The server you just launched is a static file server so it will not serve up php files for example. It will just serve your html, css and javascript files.

Node.js and http-server

Another way to launch a local webserver is to use Node.js and the http-server package. This server will do the same as what the Python server does, it will serve your static files like html, css and javascript. Let's get this this running, shall we?

First, make sure that you have Node.js installed. If you don't have it installed, go to the Node.js website and follow the instructions there. When you have Node.js set up it's time to install http-server. Open up a terminal window and type:

npm install -g http-server

If this command throws an error at you, try to run it as sudo (sudo npm install -g http-server). When the installation is complete you can navigate to your website folder, for example type cd ~/Projects/my-website if that's where your website is located. To start the server you should type the following command:

http-server

That's all, you should see output like this:

Starting up http-server, serving ./ on: http://0.0.0.0:8080

Hit CTRL-C to stop the server

You now have a local server running at  http://localhost:8080.

Using a LAMP installer

Many webservers in the wild use the LAMP stack. LAMP is short for Linux, Apache, MySQL, PHP. Apache is a webserver, MySQL is a type of SQL database and PHP is a server-side language. If you're not comfortable with the command line or plan to do PHP development I recommend to install this stack on your development machine. A good installer for this is XAMPP. When you have XAMPP installed you get a graphical interface that you can use to start / stop your webserver and database server. XAMPP will also provide you with a folder that it uses to serve your files. So if you want to use this webserver for your project you will have to move that project in to the XAMPP web folder. Your webserver can be accessed through http://localhost .

Other ways

There are plenty of other ways to start webservers or run a local development environment. Especially if you're doing a lot more than just developing some html, css and javascript files. Personally I have used all three of these methods to launch webservers when I needed to quickly test something, so I figured I'd share these. Especially people who are struggling with loading external resources or want to approach the real word a little bit more in their experiments can benefit from these examples.

If you feel like I forgot a method or maybe I forgot to mention something important, send me a tweet.

Mobile-first is a great workflow

One of the first questions a client might ask you when you start talking about his new website site is "Will it be responsive?". And the answer to that question will more often than not be "Yes, it will". Especially now that Google will penalize websites that aren't mobile friendly it's important that you make sure that your site works well on mobile devices. How do you approach responsive webdesign in a good way? Even though I am not a designer I'd say mobile-first.

Different approaches to responsive web design

When you're doing a responsive webdesign there's a couple of ways to do it. Some people use Photoshop and design three different versions of their website, one for mobile phones, one for tablets and one for the desktop. Others just make one of these three and design the rest during development in the browser.

If you only design one of the three big options, which one should it be? And when you start to build the website, where do you start? Do you do the desktop version first since it's easier for you as a developer? Or do you start with the tablet version because it's in the middle of the spectrum? Or do you let the client decide and start with the one that makes them the happiest?

These are just a few of the options you have when you're doing responsive web design, there isn't a way that is forced upon you by anybody and you're free to choose whatever you feel is most efficient. But in practice there seems to be one approach in the development phase that works every time for me. That approach is mobile-first.

What is mobile-first?

Mobile-first means exactly what you probably think it means, it's when you start your process with the mobile phone. Ideally you will start both the design and the development phase by thinking about mobile straight away. My experience is, however, that clients prefer to see designs for how the website will look on a big screen with all the bells and whistles you might add. So designers tend to not really work from a mobile first perspective because they focus on what the client likes to see. This probably doesn't apply to every designer and every client but it does apply to most designers and clients I've worked with.

When you enter the development phase, the approach you take is in your hands, you can decide where to start. And deciding to start mobile first isn't just a matter of preference. There are very valid reasons to approach the development phase from a mobile-first perspective.

Why mobile-first?

When you are building a responsive website there's a lot of things to consider, how does this look on a screen that is X wide? Should module Y be visible on that screen? Thinking about everything for every screen is overwhelming, there's so much going on and you get so little for free when you're building a website. So you're going to have to start somewhere and I prefer that somewhere to be the smallest screen I will develop for.

Constraints

A mobile phone is not only the smallest, but also the most constraint and possibly even the most used device that people use to browse your website with. Obviously this doesn't apply to every website in the world but do not underestimate the amount of mobile browsing people do. Because of these factors it makes sense to first perfect the browsing experience on the small screens.

And since it's also the most constrained browsing experience you will have to focus on the parts of your app that really matter to your users. This will make sure that you don't just add a lot of noise because it might look cool or pretty.

Development speed

If you've made a responsive website before from a desktop first approach you probably noticed that you had to 'undo' a lot of your styling and scripting. I'd like to illustrate this with a little bit of code. The code will take an unsorted list and turn it into a nice navigation bar for the desktop view. On mobile the list will be shown as a list.

.nav-list {
    list-style: none;
    margin: 0;
}

.nav-list li {
    padding: 0;
    display: inline-block;
}

@media (max-width: 600px) {
    .nav-list li {
        display: list-item;
    }
}

Do you notice how we first set .nav-list li  to a non-default value, inline-block  and then on screens smaller than 600 pixels we set .nav-list li  back to it's default value. Let's rewrite this from a mobile-first perspective.

.nav-list {
    list-style: none;
    margin: 0;
}

.nav-list li {
    padding: 0;
}

@media (min-width: 600px) {
    .nav-list li {
        display: inline-block;
    }
}

This is a small example so the difference isn't dramatic but the implications are significant. Instead of adding and removing styles we are simply adding more styles when the screen is at least 600 pixels wide. By taking this approach it's much more clear what's going on and it's also harder to make mistakes.

With the navigation list example in mind, imagine that we want to add a border and some padding to the list items, but only for the desktop view. Let's compare both approaches again, shall we?

desktop first

.nav-list {
    list-style: none;
    margin: 0;
}

.nav-list li {
    padding: 1em;
    border: 1px solid #333;
    border-radius: .5em;
    display: inline-block;
}

@media (max-width: 600px) {
    .nav-list li {
        display: list-item;
        padding: 0;
        border: none;
        border-radius: 0;
    }
}

mobile first

.nav-list {
    list-style: none;
    margin: 0;
}

.nav-list li {
    padding: 0;
}

@media (min-width: 600px) {
    .nav-list li {
        display: inline-block;
        padding: 1em;
        border: 1px solid #333;
        border-radius: .5em;
    }
}

As you can see the mobile first approach is a lot cleaner. Not only is it cleaner, it's also safer. We don't have to worry about resetting certain styles back to their defaults like we have to in our desktop-first approach.

Of course you still have to keep an eye out for cascading accidents because sometimes you set something for mobile that will have to be reset for your desktop view. But in my experience this happens a lot less often with mobile-first than it does with desktop-first.

Adding javascript is easier than removing it

I just showed you that when it comes to css it's a lot easier to stack on more styles than it is to reset them to defaults for mobile. The same applies for javascript. I usually find myself initializing a lot less (complex) modules for mobile. When you take a mobile-first approach with this you will not initialize certain things at first. Once you know that you're on a large screen machine you can start initializing your larger, more complex modules that are intended for desktop use.

Not only is it easier to initialize things when you know you need them, it's also a lot faster. Imagine executing some heavy javascript on a mobile phone only to find out that the module won't even be used because the target elements are hidden. That's a waste of precious resources that you might have used to get your page up and running on the device really quick.

Conclusion

In this post I explained to you what a mobile-first approach is from the perspective of a developer. I also showed you how this impacts the process of writing code. Going in mobile-first will prevent you from having to write a lot of 'reset this to default' css. It's also easier for the javascript part of your application. You won't initialize thing that you don't need and this generally makes your pages render faster as well.

I'm not saying that a desktop-first approach is worst in every case or scenario, I'm also not saying that the design process has to be mobile first. But thinking about the smallest most constrained devices does seem to result in faster and more focused websites. It also seems to lead to a more solid code base and happier developers.

Don’t depend on javascript to render your page.

Today Christian Heilmann posted this tweet, demonstrating a rather huge delay between page load and javascript execution. This huge delay made the page show things like {{venue.title}} for an awkward amount of time. Once the page has loaded for the first time you can refresh it and the {{venue.title}} won't show. What it does still show, however, is a wrong page header (the venue title is missing) and the font isn't loaded straight away either. So I guess we all agree that there's several things wrong with this page and at least one of them is, in my opinion, completely unnecessary.

What's actually going wrong here?

From what I can tell this page is using Angular.js. I'm not going to rant about Angular and what might be wrong with it, there's plenty of other people out there who do that. What I will say, however, is that the approach this website uses to rendering rather simple data is wrong. This website is serving you a webpage from their server. Then the browser has to read that page, load all assets and read them. So the page will only start looking better after all the javascript was loaded and executed. If this sound terrible to you that's because it is.

Not only did Christian post a Youtube video, he also ran the page through Web Page Test. This produced another video that shows the page loading with a timer. It takes six(!) seconds for the correct title to appear in this video. It takes twenty-five seconds for the page to be complete.  For a webpage, six second is a long time, twenty-five seconds is an eternity. People might not even stay on your page for six seconds, let alone twenty-five.

So why is the page this slow? Angular is pretty fast, or at least computers are fast enough to make what Angular does really fast. So something fishy must be going on here. Let's use some inspector tools to find out what this page is doing and where it's spending time at.

Loading the page and assets

When loading the page using Safari with timelines enabled we can see how this page is loading it's assets and how rendering is going on. The first thing I'll look at is the networking section to get an idea of how everything is being loaded.

Schermafbeelding 2015-03-14 om 11.11.42

As you might expect, the browser will first load the page itself. The page is 10KB, which isn't bad. A website like reddit weighs in at about 125KB. Then the styles load, they're about 240KB, rather large. Especially if you consider what the page looks like. Then a 5KB print stylesheet is loaded as well, nothing wrong with that.

And then comes an almost 500KB(!) libraries file. That's huge. Like, really huge. That file alone almost takes a full second to load over my fast cable connection.

At the 577ms mark we start loading the actual information that should be displayed on the page. There's a full second of latency before that file starts loading. And once that file is loaded (and parsed) the title can be displayed. This result is a little different from the web page test, probably because I have really fast internet and a fast machine and maybe a bit of luck was involved as well, but almost two full seconds before anything happens is a long time. That's almost two seconds after the initial page loaded.

What does this mean?

The analysis that I've done above isn't very in-depth, and to make my point it doesn't have to be. What the above statistics tell us that it took the webpage almost two seconds to go from loading html to displaying a rendered page. Not everything on the page was loaded properly yet, it just took about two seconds to go from {{venue.title}} to displaying the venue's actual title. What if I told you that there's no good reason for this to take two seconds or even six seconds in the web page test video? And what if I tell you that I could get that title on the page in about zero seconds?

Doing this better

The title of this article says that you shouldn't rely on javascript to render your page and I believe that the better.org.uk is a perfect example of this. This website could be improved an insane amount if they would just render that initial view on their server. I don't see single valid reason for the server to not pick up that .json file containing the venue info, parse it and put it's contents on the page. Doing this would result in {{venue.title}} not even being in the html at all. Instead it will contain the actual venue title. This goes for all the venue info on the page actually. Why load that after loading the page and all the javascript and waiting for the javascript to be parsed? There are times where you might want to do something like this but that's usually after user interactions. You might want to use javascript to load a list of search results while a user is typing to provide real-time searching for example. But I don't think javascript should be used to load page critical information, that's the server's job.

Wrapping this up

The example I used is a really slow website, not all websites are this slow and some website don't suffer from that flash of {{venue.title}}. But my point still stands for those websites, they are slower than they need to be because they load page critical data after the page is loaded. I want to thank Christian Heilmann for tweeting about this issue and allowing me to use his resources for this post. This issue seems to be a real one and everybody seems to forget about it while they fight over which framework is the best, fastest and most lightweight. Not depending on the framework to render your page is the fastest, best and most lightweight way there is. You can find me on Twitter if you have pointers, corrections or opinions on this. Thanks for taking the time to read this!

Automagically load your Gulp plugins

When I first started using gulp I felt that the most annoying thing about it all was that I had to manually require  all my plugins. So on a large project I would get 20 lines of requiring plugins. Soon I was looking for a solution that would allow me to include plugins automatically and thankfully I found one that's extremely easy to use. It's called gulp-load-plugins.

Using gulp-load-plugins

In order to use gulp-load-plugins you must first install it through npm. Open up a terminal window and type npm install --save-dev gulp-load-plugins if it fails due to permission errors you might have to run the command as sudo . When the plugins is installed you can use it inside your gulpfile like this:

var gulp = require('gulp');
var plugins = require('gulp-load-plugins')();

gulp.task('scripts', function() {
    gulp.src("/scripts/src/*.js")
        .pipe(plugins.plumber())
        .pipe(plugins.concat('app.js'))
        .pipe(plugins.uglify())
        .pipe(gulp.dest("/scripts/"))
});

On line 2 gulp-load-plugins is being included. Note that we immediately call  this module as well by adding parentheses after requiring it. When you call the plugin it looks through your node_modules  and it adds every module that starts with gulp- to itself as a callable function. So if you have gulp-uglify installed you can just call plugins.uglify .

When you have a gulp plugin that has a name with dashes in it, like gulp-minify-css . The loader will add it as minifyCss . In other words it will camelcase the plugin names. Well, that's it. This gulp plugin really helped my gulp workflow and I hope it will help you as well.