Tuesday 30 April 2019

The Simplest Ways to Handle HTML Includes

It's extremely surprising to me that HTML has never had any way to include other HTML files within it. Nor does there seem to be anything on the horizon that addresses it. I'm talking about straight up includes, like taking a chunk of HTML and plopping it right into another. For example the use case for much of the entire internet, an included header and footer for all pages:

...
<body>
   <include src="./header.html"></include>

   Content

   <include src="./footer.html"></include>
</body>
...

That's not real, by the way. I just wish it was.

People have been looking to other languages to solve this problem for them forever. It's HTML preprocessing, in a sense. Long before we were preprocessing our CSS, we were using tools to manipulate our HTML. And we still are, because the idea of includes is useful on pretty much every website in the world.

Use PHP

Can you use PHP instead?

...
<body>
   <?php include "./header.html" ?>

   Content

   <?php include "./footer.html" ?>
</body>
...

This will perform the include at the server level, making the request for it happen at the file system level on the server, so it should be far quicker than a client-side solution.

Use Gulp

What's even faster than a server-side include? If the include is preprocessed before it's even on the server. Gulp has a variety of processors that can do this. One is gulp-file-include.

That would look like this:

...
<body>
   @@include('./header.html')

   Content

   @@include('./footer.html')
</body>
...

And you'd process it like:

var fileinclude = require('gulp-file-include'),
  gulp = require('gulp');
 
gulp.task('fileinclude', function() {
  gulp.src(['index.html'])
    .pipe(fileinclude({
      prefix: '@@',
      basepath: '@file'
    }))
    .pipe(gulp.dest('./'));
});

Looks like this particular plugin has fancy features where you can pass in variables to the includes, making it possible to make little data-driven components.

Use Grunt

This is what the grunt-bake plugin does. You'd configure Grunt to process your HTML:

grunt.initConfig({
    bake: {
        your_target: {
            files: {
                "dist/index.html": "app/index.html",
            }
        }
    }
});

Then your HTML can use this special syntax for includes:

...
<body>
   <!--(bake header.html)-->

   Content

   <!--(bake footer.html)-->
</body>
...

Use Handlebars

Handlebars has partials.

You register them:

Handlebars.registerPartial('myPartial', '')

Then use them:


There is also fancy features of this that allow for evaluation and passing data. You'll still need a processor to run it, probably something like gulp-handlebars.

Speaking of templating languages which make use of curly braces... Mustache has them, too.

Use Pug

Pug is an HTML preprocessor that has a whole new syntax for HTML that is a bit more terse. It's got includes though.

...
body
   include ./header.html"

   p Content

   include ./footer.html"

   ...

Then you run it with something like gulp-pug.

Use Nunjucks

I love me some Nunjucks! Nunjucks has includes. You'd do it like this:

...
<body>
   Liquid error: This liquid context does not allow includes.

   Content

   Liquid error: This liquid context does not allow includes.
</body>
...

If you put that in a file called index.njk, you could process it with a simple Node script into index.html like this:

const nunjucks = require("nunjucks");
const fs = require("fs");

fs.writeFile("index.html", nunjucks.render("index.njk"), function(err, data) {
  if (err) console.log(err);
  console.log("Compiled the Nunjucks, captain.");
});

Or process it with something like gulp-nunjucks.

11ty has Nunjucks built-in, along with many of the other mentioned so far. Might be good for you if you're actually building a little site.

Use Ajax

Say you had...

<body>
  
  <header></header>
  
  Content.
  
  <footer></footer>

</body>

You could fetch the contents for the header and footer from respective files and dump the contents in.

fetch("./header.html")
  .then(response => {
    return response.text()
  })
  .then(data => {
    document.querySelector("header").innerHTML = data;
  });

fetch("./footer.html")
  .then(response => {
    return response.text()
  })
  .then(data => {
    document.querySelector("footer").innerHTML = data;
  });

Speaking of JavaScript... If you're building your site using a JavaScript framework of just about any kind, building through components is kind of the main deal there and breaking parts you want to include in other files should be no problem. Some kind of import Header from "./header.js"; and <Header /> is the territory you'd be in in React land.

Use iframes

You could do this:

<body>
  
  <iframe src="./header.html"></iframe>
  
  Content.
  
  <iframe src="./footer.html"></iframe>
  
</body>

But the content in those iframes does not share the same DOM, so it's a bit weird, not to mention slow and awkward to style (since iframes don't know the heights of their contents).

Scott Jehl documented a cool idea though: You can have the iframe inject the content of itself onto the parent page then remove itself.

<body>
  
  <iframe src="header.html" onload="this.before((this.contentDocument.body||this.contentDocument).children[0]);this.remove()"></iframe>
  
  Content.
  
  <iframe src="footer.html" onload="this.before((this.contentDocument.body||this.contentDocument).children[0]);this.remove()"></iframe>
  
</body>

Use Jekyll

Jekyll is a Ruby-based static site generator with includes. You keep your includes in the /_includes/ folder, then:

<body>
  Liquid error: This liquid context does not allow includes.
  
  Content.

  Liquid error: This liquid context does not allow includes.
</body>

Jekyll is a big one, so I'm calling it out here, but there are a ton of static site generators and I'd wager any of them can do includes.

Use Sergey

OK, I'll call out one more SSG because it's new and super focused. Sergey has a web components style format:

<body>
  <sergey-import src="header" />

  Content.

  <sergey-import src="footer" />
</body>

You'd name the files header.html and footer.html and put them in /includes/ and then it'll make a build with the includes processed when you run the npm script it has you do.

Use Apache SSI

Apache, a super duper common web server, can do includes. You do it like this:

<body>
                
  <!--#include file="./header.html" -->
  
  Content
  
  <!--#include file="./footer.html" -->
  
</body>

But you need the right Apache configuration to allow stuff. I tried my best to get a working demo going but didn't have much luck.

I tried using .htaccess within a folder on an Apache server and flipping on what I thought was the right stuff:

Options +Includes

AddType text/html .html
AddOutputFilter INCLUDES .html

I'm sure there is some way to get it working though, and if you do, it's kinda neat that it needs zero other dependencies.

Use CodeKit

Mac only, but CodeKit has a special language called Kit it processes where 90% of the point of it is HTML includes. It uses special HTML comments:

...
<body>
   <!-- @import "./header.html" -->

   Content

   <!-- @import "./footer.html" -->
</body>
...

Use Dreamweaver

Lol jk. But it really is a thing. DWTs, baby.

Holy Crap

That's a lot of ways, isn't it?

Like I said at the top, it's very surprising to me that HTML itself hasn't addressed this directly. Not that I think it would be a great idea for performance to have <include> statements that trigger network requests all over our code, but it seems in-line with the platform. Using ES6 imports directly without bundling isn't a great idea always either, but we have them. @importing CSS within CSS isn't a great idea always, but we have it. If the platform had a native syntax, perhaps other tooling would key off that, much like JavaScript bundlers support the ES6 import format.

The post The Simplest Ways to Handle HTML Includes appeared first on CSS-Tricks.



from CSS-Tricks http://bit.ly/2J5NUnc
via IFTTT

Revisiting prefers-reduced-motion, the reduced motion media query

Two years ago, I wrote about prefers-reduced-motion, a media query introduced into Safari 10.1 to help people with vestibular and seizure disorders use the web. The article provided some background about the media query, why it was needed, and how to work with it to avoid creating disability-triggering visual effects.

The article was informed by other people’s excellent work, namely Orde Saunders’ post about user queries, and Val Head’s article on web animation motion sensitivity.

We’re now four months into 2019, and it makes me happy to report that we have support for the feature in all major desktop browsers! Safari was first, with Firefox being a close second. Chrome was a little late to the party, but introduced it as of version 74.

This browser support data is from Caniuse, which has more detail. A number indicates that browser supports the feature at that version and up.

Desktop

Chrome Opera Firefox IE Edge Safari
74 No 63 No No 10.1

Mobile / Tablet

iOS Safari Opera Mobile Opera Mini Android Android Chrome Android Firefox
10.3 No No No No No

While Microsoft Edge does not have support for prefers-reduced-motion, it will become Chrome under the hood soon. If there’s one good thing to come from this situation, it’s that Edge’s other excellent accessibility features will (hopefully) have a good chance of being back-ported into Chrome.

Awareness

While I’m happy to see some websites and web apps using the media query, I find that it’s rare to encounter it outside of places maintained by people who are active in CSS and accessibility spaces. In a way, this makes sense. While prefers-reduced-motion is relatively new, CSS features and functionality as a whole are often overlooked and undervalued. Accessibility even more so.

It’s tough to blame someone for not using a feature they don’t know exists, especially if it’s relatively new, and especially in an industry as fast-paced as ours. The deck is also stacked in terms of what the industry prioritizes as marketable, and therefore what developers pay attention to. And yet, prefers-reduced-motion is a library-agnostic feature that ties into Operating System-level functionality. I’m pretty sure that means it’ll have some significant staying power in terms of reward for time spent for skill acquisition.

Speaking of rewards, I think it’s also worth pointing out the true value prefers-reduced-motion represents: Not attracting buzzword-hungry recruiters on LinkedIn, but improving the quality of life for the people who benefit from the effect it creates. Using this media query could spare someone from having to unnecessarily endure a tremendous amount of pain for simply having the curiosity to click on a link or scroll down a page.

The people affected

When it comes to disability, many people just assume “blind people.” The reality is that disabilities are a complicated and nuanced topic, one that is surprisingly pervasive, deeply personal, and full of unfortunate misconceptions. It's also highly variable. Different people are affected by different disability conditions in different ways — extending to a wide gamut of permanent, temporary, environmental, and situational concerns. Multiple, compounding conditions can (and do) affect individuals, and sometimes what helps one person might hinder another. It’s a difficult, but very vital thing to keep in mind.

If you have a vestibular disorder or have certain kinds of migraine or seizure triggers, navigating the web can be a lot like walking through a minefield — you’re perpetually one click away from activating an unannounced animation. And that’s just for casual browsing.

If you use the web for work, you might have no choice but to endure a web app that contains triggering animations multiple times a week, or even per day or hour. In addition to not having the autonomy to modify your work device, you may also not have the option to quickly and easily change jobs — a privilege easily forgotten when you’re a specialized knowledge worker.

It’s a fallacy to assume that a person is aware of their vestibular disorder, or what triggers it. In fact, sometimes the initial triggering experience exacerbates your sensitivity and makes other parts of a design difficult to use. Facundo Corradini shares his experience with this phenomenon in his article, “Accessibility for Vestibular Disorders: How My Temporary Disability Changed My Perspective.”

Not all assistive technology users are power users, so it’s another fallacy to assume that a person with a vestibular disorder is aware of, or has the access rights to enable a motion-reducing Operating System setting or install a browser extension.

Think of someone working in a large corporation who has to use a provisioned computer with locked-down capabilities. Or someone who isn’t fully aware of what of their tablet is capable of doing past browsing social media, watching video, and messaging their family and friends. Or a cheap and/or unorthodox device that will never support prefers-reduced-motion feature — some people purchase discontinued devices such as the Windows Phone specifically because their deprecation makes them affordable.

Do these people deserve to be hurt because of their circumstances? Of course not.

Considering what’s harmful

You can tie harm into value, the same way you can with delight. Animation intended to nudge a person towards a signup could also drive them away. This kind of exit metric is more difficult to quantify, but it definitely happens. Sometimes the harm is even intentional, and therefore an easier datapoint to capture — what you do with that information is a whole other issue.

If enough harm happens to enough people, it affects that certain something we know as branding. This effect doesn’t even need to be tied to a disability condition. Too much animation, applied to the wrong things in the wrong way will drive people away, even if they can’t precisely articulate why.

You also don’t know who might be on the receiving end, or what circumstances they’re experiencing the moment they load your website or web app. We can’t — and shouldn’t — know this kind of information, either. It could be a prospective customer, the employee at a venture capitalist firm tasked with evaluating your startup, or maybe even your new boss.

We also don’t need to qualify their relationship to us to determine if their situation is worth considering — isn’t it enough to just be proactively kind?

Animation is progressive enhancement

We also need to acknowledge that not every device that can access the web can also render animation, or render animation smoothly. When animation is used on a low-power or low quality device that “technically” supports it, the overall user experience suffers. Some people even deliberately seek this experience out as a feature.

Devices may also be set to specialized browsing modes to allow people to access your content in alternate ways. This concept is known as being robust, and is one of the four high-level principles that govern the guidelines outlining how to craft accessible experiences.

Animation might not always look the way you intend it in these modes. One example would be when the viewport is zoomed and the animation isn’t built using relative units. There’s a non-trivial chance important parts might be pushed out of the viewport, leaving the animation appearing as a random collection of flickering bits. Another example of a specialized browsing mode might be Reader Mode, where the animation may not appear at all.

Taking it to code

Considering all this, I’m wondering if there are opportunities to help web professionals become more aware of, and therefore more considerate of the downsides of poorly conceived and implemented animation.

Maybe we proactively incorporate a media query high up in the cascade to disable all animation for those who desire it, and for those who have devices that can’t support it. This can be accomplished by targeting anything where someone has expressed a desire for a low-to-no-animation experience, or any device that has a slow screen refresh rate.

The first part of the query, targeting low-to-no-animation, is done via prefers-reduced-motion. The second, targeting a screen with a low refresh rate, uses update. update is a new media feature that allows us to “query the ability of the output device to modify the appearance of content once it has been rendered.”

@media screen and
  (prefers-reduced-motion: reduce), 
  (update: slow) {
  * {
    animation-duration: 0.001ms !important;
    transition-duration: 0.001ms !important;
  }
}

This code forces all animation that utilizes a declaration of animation-duration or transition-duration to conclude at a rate that is imperceptible to the human eye. It will work when a person has requested a reduced motion experience, or the device has a screen with a slow refresh rate, say e-ink or a cheap smartphone.

Retaining the animation and transition duration also ensures that any functionality that is tied to CSS-based animation will activate successfully (unlike using a declaration of animation: none), while still preventing a disability condition trigger or creating rendering lag.

This declaration is authored with the intent of introducing some intentional friction into our reset styles. Granted, it’s not a perfect solution, but it does drive at a few things:

  1. Increasing the chances of developers becoming aware of the two media features, by way of making them present in the cascade of every inspected element.
  2. Providing a moment to consider why and how animation will be introduced into a website or web app, and what the experience should be like for those who can’t or don’t want to experience it.
  3. Encouraging developers who are less familiar with CSS to think of the cascade in terms of components and nudge them towards making more easily maintainable stylesheets.

Animation isn’t unnecessary

In addition to vestibular disorders and photosensitive conditions, there’s another important aspect of accessibility we must consider: cognitive disabilities.

Cognitive disabilities

As a concern, the category is wide and often difficult to quantify, but no less important than any other accessibility discipline. It is also far more prevalent. To expand on this some, the World Health Organization reports an estimated 300 million people worldwide are affected by depression, a temporary or permanent, environmental and/or biological condition that can significantly impair your ability to interact with your environment. This includes interfering with your ability to understand the world around you.

Animation can be a great tool to help combat some forms of cognitive disability by using it to break down complicated concepts, or communicate the relationship between seemingly disparate objects. Val Head’s article on A List Apart highlights some other very well-researched benefits, including helping to increase problem-solving ability, recall, and skill acquisition, as well as reducing cognitive load and your susceptibility to change blindness.

Reduce isn’t necessarily remove

We may not need to throw the baby out with the bathwater when it comes to using animation. Remember, it’s prefers-reduced-motion, not prefers-no-motion.

If we embrace the cascade, we can work with the animation reset code described earlier on a per-component basis. If the meaning of a component is diminished by removing its animation altogether, we could slow down and simplify the component’s animation to the point where the concept can be communicated without potentially being an accessibility trigger.

If you’re feeling clever, you might even be able to use CSS Custom Properties to help achieve this in an efficient way. If you’re feeling extra clever, you could also use these Custom Properties for a site-wide animation preferences widget.

In the following code sample, we’re defining default properties for our animation and transition durations, then modifying them based on the context they’re declared in:

/* Set default durations */
:root {
  --animation-duration: 250ms; 
  --transition-duration: 250ms; 
}

/* Contextually shorten duration length */
@media screen and (prefers-reduced-motion: reduce), (update: slow) {
  :root {
    --animation-duration: 0.001ms !important; 
    --transition-duration: 0.001ms !important;
  }
}

@media screen and (prefers-reduced-motion: reduce), (update: slow) {
  /* Remove duration for all unknown animation when a user requests a reduced animation experience */
  * {
    animation-duration: var(--animation-duration);
    transition-duration: var(--animation-duration);
  }
}

/* Update the duration when animation is critical to understanding and the device can support it */
@media screen and (prefers-reduced-motion: reduce), (update: fast) {
  .c-educational-concept {
    /* Set a new animation duration scoped to this component */
    --animation-duration: 6000ms !important; 
    ...
    animation-name: educational-concept;
    /* Use the scoped animation duration */
    animation-duration: var(--animation-duration); 
  }
}

However, trying to test the effectiveness of this slowed-down animation puts us in a bit of a pickle: there’s no real magic number we can write a test against.

We need to have a wide representation of people who are susceptible to animation-based disability triggers to sign off on it being safe, which unfortunately involves subjecting them to something that may potentially not be. That’s a huge ask.

A better approach is to ask about what kinds of animation have been triggers for them in the past, then see if what they describe matches what we’ve made. This approach also puts the onus on yourself, and not the person with a disability, to do the work to provide accommodation.

If you’re having trouble finding people, ask your friends, family, and coworkers — I’m sure there’s more people out there than you think. And if you need a good starting point for creating safer animation, I once again urge you to read Val’s article on A List Apart.

Neurodivergence

There’s a lot to unpack here, and I’m not the most qualified person to talk about it. Here’s what my friend Shell Little, an Accessibility Specialist at Wells Fargo DS4B, has to say about it:

Web animation as it relates to Neurodivergence (ND) can be a fantastic tool to guide users to solidify meaning and push understanding. The big issue is the same animation that can assist one group of ND users can create a barrier for another. As mentioned by Eric, Neurodivergence is a massive group of people with a vast range of abilities and covers a wide variety of cognitive disabilities including but not limited to ADHD, autism, dyslexia, epilepsy, dyscalculia, obsessive-compulsive disorder, dyspraxia, and Tourette syndrome.

When speaking about motion on the web it’s important we think specifically about attention-related disabilities, autism, and sensory processing disorders that are also closely linked to both. These groups of people, who coincidentally includes me, are especially sensitive to motion as it relates to understanding information and interacting with the web as a whole. Animations can easily overwhelm, distract, and frustrate users who are sensitive to motion and from personal experience, it can even do all three at once.

Because so many people are affected by motion and animation on the web the W3C’s WCAG have a criterion named Pause, Stop, Hide that is specifically written to guide content creators on how to best create accessible animations. My main issues with this guideline are, it only applies to animations that last longer than 5 seconds and motion that is deemed essential is exempt from the standard. That means a ton of animations that can create barriers such as distraction, dizziness, and even harm are out there in the wild.

It makes sense, as Eric mentioned, that we can’t get rid of all animation. Techniques such as spinners let users know the page is still working on the task it was given, and micro-interactions help show progression. But depending on someone’s brain, the things that are helpful at lunch can be a barrier later that night. Someone’s preferences and needs shift throughout their day, and that’s the beauty of prefers-reduced-motion. It has the potential to be what fills the gaps left by Pause, Stop, Hide and allow users to decide when they do or do not want to have motion. That right there is priceless to someone like me.

As someone with an attention-related disability, an interaction I have found to be exceedingly frustrating is autoplay. Many media sharing sites have auto-playing content such as videos, gifs, and ads but because they can be paused, they pass the WCAG standard. That doesn’t mean they aren’t a huge barrier for me as I can’t read any text around them when they are playing. This causes me to have to pause every single moving item I run into. This not only significantly slows me down, and eats away at my limited spoons, but it also derails my task flow and train of thought. Now, it is true some sites — such as Twitter and LinkedIn — have settings to turn autoplay off, but this isn’t true for all sites. This would be a perfect place for prefers-reduced-motion.

In a world where I would be able to determine when and if I want videos to start playing at me, I would be able to get more done with less cognitive strain. prefers-reduced-motion is freedom for me and the millions of people whose brains work like mine. In sum, the absolute best thing we can do for our users who are sensitive to motion is to put a system in place that empowers them to decide when and where animation should be displayed to them. Let the user decide because they will always know their access needs better than we do.

Thanks, Shell!

I don’t hate fun, I just don’t want to hurt people

On my own time, I’m fortunate enough to be able to enjoy animation. I appreciate the large amounts of time and attention involved with making something come alive on the screen, and I’ve definitely put my fair share of time ooh-ing and aah-ing over other people’s amazing work in CodePen. I’ve also watched enough DC Animated Universe to be able to instantly recognize Kevin Conroy’s voice — if you’re looking for even deeper nerd cred, Masaaki Yuasa is a seriously underrated animator.

However, I try to not overly rely on animation as a web professional. There’s a number of factors as to why:

  1. First is simply pushing on awareness of the concerns outlined earlier, as many are unaware they exist. Animation has such a crowd-pleasing gee-whiz factor to it that it’s often quickly accepted into a product without a second thought.
  2. Second is mitigating risk. Not adhering to the Web Content Accessibility Guidelines (WCAG) — including provisions for animation — means your inaccessible website or web app becomes a legal liability. There is now legal precedent for the websites and web apps of private companies being sued, so it’s a powerful metric to weigh your choices against.
  3. Third is user experience. With that gee-whiz factor, people tend to forget that being forced to repeatedly view that super-slick animation over and over again will eventually become a tedious chore. There’s a reason why we no longer make 90s-style loading screens (content warning: high-contrast strobing and flickering, Flash, mimes). If you need a more contemporary example, consider why Netflix lets us skip TV show intros.
  4. Fourth is understanding the lay of the land. While prefers-reduced-motion is getting more support, the majority of it is on desktop browsers, and not mobile. We’re not exactly a desktop-first world anymore, especially if you’re in an underserved community or emerging market. A mobile form factor also may exacerbate vestibular issues. Moving around while using your device means you may lose a fixed reference point, unlike sitting at a desk and staring at a monitor — this kind of trigger is similar to why some of us can get seasick.
  5. The fifth factor is a bit of a subset of the fourth. Animation eats device data and battery, and it’s important to remember that it’s the world wide web, not the wealthy Western web. The person using your service may not have consistent and reliable access to income or power, so you want to get to know your audience before spending their money for them.

The ask

Not everyone who could benefit from prefers-reduced-motion cares about accessibility-related content, so I’d love to see the media query start showing up in the code of more popular sites. The only real way to do this is to spread awareness. Not only of the media query, but more importantly, understanding the nuance involved with using animation responsibly.

CSS-Tricks is a popular website for the frontend industry, and I’m going to take advantage of that. If you feel comfortable sharing, what I would love is to describe what kinds of animation have been problematic for you, in either the comments or on Twitter.

The idea here is we can help build a reference of what kinds of things to be on the lookout for animation-wise. Hopefully, with time and a little luck, we can all help make the web better for everyone.


Thanks to Scott O’Hara, Zach Leatherman, Shell Little, and Geoff Graham for reviewing this article.

The post Revisiting prefers-reduced-motion, the reduced motion media query appeared first on CSS-Tricks.



from CSS-Tricks http://bit.ly/2vtB5Ll
via IFTTT

Using the SERP to build your keyword list

Monday 29 April 2019

Perceived Velocity through Version Numbers

HTML5 and CSS3 were big. So big that they were buzzwords that actually meant something and were a massive success story in pushing web technology forward. JavaScript names their big releases now too: ES6, ES7, ES8... and it seems like it will keep going that way.

But HTML and CSS are done with that game. Shortly after the whole HTML5/CSS3 thing, the message was that there will be no HTML6/CSS4. There are reasons for that, like perhaps it's healthier for CSS modules to evolve independently of some global versioning number.

That said... as Dave says:

... the lull in excitement since those days is palpable....

People aren't equally excited about the big three languages of the web.

I’m on a bit of a quest to understand why these three technologies built to work together are so unequally yoked in popularity and their communities polarized from one another. One end of the spectrum experiences a boom while the other experiences a bust. The rising tide does not lift all boats.

Surely a major version number release for HTML and CSS could spark a ton of fresh enthusiasm.

I'll help. HTML6 could have HTML imports for web components, <include>, and a multi-select. CSS4 gets container queries, subgrid, standardized form control styling, and transitions to auto dimensions.

Direct Link to ArticlePermalink

The post Perceived Velocity through Version Numbers appeared first on CSS-Tricks.



from CSS-Tricks http://bit.ly/2GQrJQq
via IFTTT

The Nantwich Electrician



Oh, the Many Ways to Make Triangular Breadcrumb Ribbons!

Use the Power of Social Media Advertising to Build a Stronger Business

It’s hard to attract someone’s attention if they’re not looking in your direction. They might turn around eventually, maybe, if you’re lucky, or they might not. Social media advertising works in much the same way. If customers don’t actually see your ad, all that cost and effort will be for nothing.

We’ve noticed a trend among our clients. More and more are reaching out to us for help with their digital marketing. Business posts and pages are simply not getting seen by their audience. Interaction can be as low as 2%. It could be that the post is too general or, most likely, it’s dropping in front of the wrong people at the wrong time.

The good news is that the team at TRCREATIVE can turn this around with our experience in creating well-structured and targeted social media advertising campaigns. And luck has nothing to do with it.

There are 2.32 billion monthly active Facebook users worldwide. Admittedly, that seems like an overwhelming crowd of people but it’s also a lucrative crowd. With that number of users, you’ll most definitely find an audience who wants to connect and engage with your business or organisation.

We cut through the crowd

Fortunately, we know how to cut through the two-billion-something chatter and have a direct conversation with those who are interested in what you have to say or sell.

 

Our latest social media advertising campaigns were a sell-out success for one of our clients, owners of a hotel, restaurant and wedding venue. They asked us for our help and we tailored the ads to suit their events. The first one was a Mother’s Day lunch. We set up and promoted this event on Facebook as well as creating offline media (posters) to display around the premises. The result was a 30% increase in bookings in comparison to the previous year making it a sold-out event.

Hot on the heels of this success we managed the hotel’s second event, which was a Spring Night Party. It was sold out during the course of a three-week digital marketing campaign.

How did we do this? We target the right audience based on gender, age and location and we send them in the direction of your business. We can create a call-to-action ad that allows your audience to make a booking or make a purchase, or drive them to your website. Here’s what else we can do:

  • We use the advanced targeting tools to reach a more specific audience
  • We choose the advertising objectives that work within your budget
  • We can show your ads across social media, not just Facebook, to reach a wider audience
  • We pick the creative to suit your brand
  • We know the latest advertising features available to keep you ahead of the competition

Facebook algorithm changes mean it is more important than ever to get your digital marketing right. In light of this, we make sure your advertising is structured properly and laser-targeted. We make sure you get your money’s worth and more. The power of social media advertising can make your business go from strength to strength, starting from today. Get in touch and we’ll show you how.



from TRCREATIVE http://bit.ly/2vuo4RY
via IFTTT

Friday 26 April 2019

Interviewing for a Technical Position Doesn’t Have to Be Scary

Jacob Schatz (@jakecodes) is a staff engineer over at GitLab and was kind enough to share how he conducts job interviews for technical positions and his thinking process for them. Technical interviews are talked about often and can be a touchy subject for some, so it’s worth noting that this article expresses Jacob’s own opinions and are not necessarily shared by his employer.

Are you an interviewee who is terrified, exhausted, sad, or disappointed? I'd love to change that stigma.

I believe that people can have a great interview experience, and that I can simultaneously find the right candidate. Both things can happen at the same time! After your interview process is over, in a perfect world, regardless of outcome, you should feel good about yourself and the process. You might feel sad that you didn't get the job or excited to start your new job, but you should understand why in either situation.

At GitLab, I was put in charge of hiring very early on, and as such, I've seen thousands of resumes. When I first joined, I was asked to hire and form a team of front-end developers. I was employee #29 (we now have 500+), and I was the first front-end developer, so there was no hiring process for our team. We gradually created a process.

This article is aimed at both the interviewee, and interviewer. For the interviewee, I want you to know what a perfect interview can be like. Interviewing should not be scary or intimidating. This is a guide you can follow to do your part in creating the perfect interview. If you are an interviewer, maybe you have perfected your process. This is my view on how interviews can go in a perfect world. There are all different types of interviews, and this article focuses on interviewing developers of all experience levels. Over the years, I’ve latched on to some great processes, and this article is a behind-the-scenes look at that process for both sides of the candidacy.

Before I begin, it's important to remember that everyone is human and humans are not perfect. There are no perfect developers. Treat everyone like a regular human being. It's OK to be amazed at what some people are doing, but not OK to worship others. Talent is both congenital and acquired and you can acquire it too. Your interviewer and you are both imperfect. Interviews should not be focused around perfection. Here's what interviews should be.

Five things I look for in a candidate

The GitLab Values cover a lot of great points and you should read it. This is loosely based on those.

As an interviewer, I can only focus on so many things at once while being a productive, active listener. But I do have five specific things I am try to focus on:

  1. Does this person have a "good head on their shoulders"?
  2. Is this person technically where they need to be for this role?
  3. Is this person going to be self sufficient in this role?
  4. Does this person communicate well and will they communicate well with the team?
  5. Does this person handle positive and negative feedback well?

There are other things I'm looking for, of course, but these five things are enough to get you the job you want if you’re interviewing with me.

Forget nervousness. I won't ever hold it against you. I know you may be nervous, and that's totally fine. There is the rare occasion that nervousness becomes a debilitating factor, and in those cases, I just ask that you reschedule. Just don't hang up on me!

Recognize there's going to be bias

We have training on bias at GitLab. One thing I learned from the training is that everyone is biased, whether or not you think you are. At one point, I had the idea of doing blind interviews like they do for some orchestras. We never implemented it (and it would be tough) but that's why I keep a list of questions and a summary of what I want to cover in each interview. Each interview has a script I can follow. Everything is as repeatable and similar as possible. As the interview progresses, I'll be able to tell if I can hit the harder questions. Harder questions are not there to disqualify people, but to qualify people. If you get to my hard questions it means you have a ton of experience and knowledge under your belt. It's really important to know that I must ask trivia questions in some form but I don't qualify candidates based on trivia questions. It's about figuring the depth of your JavaScript knowledge and programming in general.

That being said, there is still one trivia question no one has ever gotten right. I'll just keep asking it, and I am sure some day, someone will get it. Trivia questions are fun, because I am a major JavaScript dork. I just love talking about all the ins and outs of JavaScript. I am looking for people that can be my coding buddy. Hiring people is about finding other people you can work with, not people that will work for you.

I want to know you're technically sound

This may be people's worst fear. The part of the interview where we ask questions like, "Why are manholes round?" The truth is that some companies may ask the medium-to-hard questions from LeetCode, and some may never ask any technical questions.

What I'm looking for in your skillset

Experience speaks louder than any technical interview question I can ask. For example, if I'm hiring for a front-end engineering role and someone tells me they built their own cool things that we can talk about, then that's awesome. I still may need to throw some more questions their way after that, or maybe the demo answers all my questions (though unlikely, but possible). But if we can walk through the code of something that you are super proud of, that’s great.

It’s helpful if you can tell me about something that you built for another company where I can see your code, or you can explain it sufficiently enough. What were the challenges? How did you deal with 10,000 comments? How did you deal with mobile? What were some challenges? I'll give you an example: You built the comment system for GitLab. For the comment system, an interesting challenge was dealing with loading users for the @ drop-down to mentioning other users. It turns out that the JSON payload for that drop-down can get quite large and loading it on page load makes the page load significantly slower. But loading that data on the first @ keypress is also slow because the payload can be more than 10 MB. We want the user to have a seamless experience and not realize the data needs time to load. So, a good way to talk about that experience would be to describe some of the approaches you considered, like:

  1. Load the data when the comment box first appears in the viewport.
  2. Load the data on the user's first mouseover of the textarea.
  3. Load the data once the user starts scrolling with enough momentum.

That last one isn't a boring solution, but is something I've heard someone say in an interview.

I might ask about algorithms and data structures

Hey interviewers, are you hiring someone for your marketing site? Don't ask them the hardest algorithms and data structure questions. Yes, algorithms and data structures play a huge part in everything, but it's more important that the candidate knows about responsive design, and maybe animations, and performance. Since we are talking about performance, they should know about Big O notation. They should know what causes re-paints. Look at Firefox Monitor and compare it to Salesforce. Everything about the Firefox site is much more snappy. Why is it more snappy? Why is the Salesforce site so chunky and slow? Resize them... oy vey! Big O would probably help you explain some parts, but being able to explain the whole picture is important.

Quick aside on Big O notation since I brought it up.

Big O is a way of describing the time your code will run in and/or the memory space your code will take up in a worst case scenario. I think it's really great to learn, and helps out in every day programming. You can and should learn it, which might take about an hour. After one hour, done or not, you’ll more than likely be prepared for any legitimate Big O question that interviewers would ask.

Big O is not something you need to take a course on. Here are some articles that can explain it to you in under an hour:

OK, back to algorithms and data structures in interviews.

Since there's a chance these types of questions will come up, it's worth doing a little homework in advance. There are two typical gold standards when studying for interviews that ask about algorithms and data structures.

There are many other things that are recommended for algorithm and data structure, heavy coding interviews, but rather than memorizing every example in the world (which won't solve any problems for you), it's better to learn how to solve these problems.

As I said above, front-end engineers should learn Big O for their health, because it's good for you, like eating your Wheaties. Interviewers should not ask extensive algorithms and data structure questions unless the job requires extensive knowledge of them. If I was designing a front-end framework, say like Vue, it would be important to optimize a DOM diffing algorithm or at least understand the implementation of the algorithm you are using. But does that mean I would ask seven extra hard questions from a CTCI? No. You are testing for understanding, not for memorization. When people work through these questions (when I ask them), I want to see that they thought through the problem and we worked it out together more than I want to see that they got the right answer. It's all about figuring out what you will be able to do, as an engineer, when you get the job — not what you memorized yesterday. A person who has knowledge of algorithms is going to be better at implementing them than someone who has to learn them on the job.

Are you hiring someone to build a dependency management system? This person needs to know a lot about algorithms and data structures.

These are two extreme ends of the spectrum, but in my opinion, not everyone needs to know how to write a red-black tree from scratch — but everyone should understand Big O. However, it will dramatically improve your skills as a software developer to learn typical algorithms and data structures.

When I do ask algorithm and data structure questions here are a few I do ask:

  • What is a linked list and can you show me how to implement one with and without an array in JavaScript?
  • What is the difference between BFS and DFS and can you implement one of them?

Getting these wrong will not disqualify anyone. Remember, I don't use trivia to qualify people.

Do you have a good head on your shoulders?

There are a lot of soft skills I'm looking for as well during the interview. It's my way of determining whether you have a "good head on your shoulders."

Pedantically speaking, that means you make good decisions, but it's much more than that to me. People who have a good head on their shoulders make sound decisions. It's good to have different opinions than me, but there is a standard of knowledge we should agree on. For example, we should all agree that laying out an entire blog with only absolute positioning is a bad idea. That is not a sound decision.

But I might create a scenario like this to check on those skills:

Let's go into CodePen and create a static blog homepage. We'll need a navigation menu, and we'll need a place for the title and article, and then at the bottom let's have some comments and a footer.

I'd then talk you through different ways you could create the navigation and the pros and cons to each. For a lot of the front-end developers I hire, I'd like to know that they know some core JavaScript so I might ask them add some small functionality using only vanilla JavaScript.

When a framework does everything for you, you don't need to do things yourself. I want to know that you get the whole picture.

A “good head on you shoulders" is a fancy way of telling me that you have your crap together. This is not an exhaustive list, but are the types of things that catch my attention:

  • You take care of yourself
  • You speak professionally (this has more of an impact than most people know)
    • Leave out super personal details
    • Answer questions succinctly
    • Take time to think
    • Say, "I don't know," when you don't know
    • Be confident, but not cocky, even if you aren't
  • You finish what you start
  • You are honest
  • You are able to say no
  • You know what you want and you want to help others get what they want
  • You'll disagree and even debate, but know when to let something go
  • You are able to effectively communicate in an interview
    • Is this conversation easy or exhausting?
    • Are you fluent in English? Accents are totally OK!
    • Do you grasp the concepts being discussed?
  • You’re a kind person.

On that last point: kindness doesn't mean you are a pushover. Kindness is a major part of challenging others and giving feedback.

I want to see that you are self-sufficient

It seems obvious now, but I am convinced — after working at GitLab — that self-sufficiency is what interviewers should seek in everyone being hired. Self-sufficiency plays a big part in your role in the company.

For example, to go extreme, think about a GM, who may have the least amount of external direction of anyone on a team. Everyone has responsibilities, but a GM must often be good at many things, including (but not limited to) marketing, sales, and management. All this changes based on the size of the team. Their role may be the most vague. They are very self-sufficient. A senior developer (in my opinion) should be able to take on an entire large piece of functionality and implement it properly.

This is not to say a developer shouldn't communicate during the process. They should ask questions, and pair with other people to find the best way forward.

Reviewing an interviewee’s code has the opportunity to be boring (in a good way) as we know what to expect from them. We are relying on them to mentor less experienced developers. Junior developers should be self sufficient too, but probably won't take on large initiatives alone. Junior developers often work great in small chunks. For example, it might be a great thing for a junior developer to take on the smaller tasks that a senior developer has on a larger project. Senior developers can also mentor junior developers and nudge them in the right direction to help them become more self-sufficient, which is a great thing for both parties — and also a great thing for the manager, as they can delegate more work to a senior developer.

If you are a front-end developer and need hand-holding at this point in your career, that is totally 100% OK, and everyone has been there. Or, if you are applying to a lot of places and not getting anywhere, and are extremely frustrated: I suggest that you become a little more self-sufficient before you apply. One way I suggest to become more self-sufficient and nab that job you want: Forget code examples, little shopping cart apps, and their ilk, as they don't fair well for job interviews. Build something full-fledged for someone and do it for cheap or free. Find a church, synagogue, homeless shelter or someone near you and offer to make them a website.

Just remember that free clients are often the worst clients. It will be worth it when you can say that you've done work for a few clients. For bonus points, document your work in a few blog posts. This stuff looks great on resumes and will make you stick out from the rest. I know that anyone can get an easy website through Wix or other site building platforms, but there's nothing like a wonderful custom-designed website. I think I made around 10 or so websites before I had my first programming job. I could fill a book with crazy stories from those times.

Communication and feedback is key

This is another point that seems obvious, but is hard to do right. Communication is well documented in the GitLab Handbook so I won't cover it, except to say that I follow GitLab's values and we are looking for others who desire to follow those values as well. Positive and negative feedback is also well documented in the GitLab Handbooks, so I won't cover it here.

How I go about the rest of the interview

Because we interview a lot of candidates at GitLab, we follow a common flow so we can repeat it easily. I won't go into specifics about our interview process, because it's constantly evolving. But, in general, this is the flow I follow.

Tell me about yourself

You'll get asked the famous question that goes along the lines of "tell me about yourself," "tell me what you've been doing," or "tell me about your time at [Company Name]." When I ask this question, I am trying to find the connection between the job you applied for and the jobs you've had in the past. It's good to find the common ground ahead of time.

Like, for example, as an employee of GitLab, if I were personally applying to a FAANG as a front-end engineer, I am sure both GitLab and that company are trying to get page load times to be faster. Maybe I noticed there were 26K event listeners on a page when I first joined GitLab and was able to reduce it down to 0, decrease the loading time by 50%, down to a speed of 200ms. I am sure this would be something relevant to the conversation.

So, as an interviewee, I might say something like this:

"Hi! I am a front-end engineer at GitLab, I've been here for 3.5 years and during my tenure I've made a ton of huge improvements, some of the areas I loved working on are performance, UX design implementation, and architectural design.

You don't want to get into tons of details at this point, but it's good to give the interviewer some facts to work with. It is frustrating when I ask this question and someone goes into a 10-minute detailed account of their entire career.

What made you apply to our company?

The interviewer might ask, "What made you decide to apply to our company?" Hopefully, you are excited to work at this company — otherwise, why bother applying for it?

For some reason or another, this question often sends a candidate into overdrive and they wind up mixing up the name our company. That's perfectly normal behavior, especially if your company sounds like another company.

What I'm looking for at this point is to see whether you are just looking for a job or that you’re really excited to work with us. We want people who really want to work with us. This is when I can also see if a person knows anything about our company. For example, some people like our values, have read them and want to work at a company with these values. Some people want to solve big problems like the ones we are tackling. Some people have seen talks and read articles from our team and would love to work around smart people like them.

What are your five things?

Lastly, I like to ask if a candidate has any questions for me. This is an important part of the interview, and you should extensively think this through beforehand. Your goal is to make me respond with: “Oooohhh, great question!" On one hand, I am truly trying to answer any questions you have, so don’t be shy. On the other hand, I am also trying to gauge your interest in the job, so something like, “Uh, I dunno," is usually a big bummer to hear because it signals that maybe you’ve tuned out, or the job is not interesting to you. that’s can leave an undesirable aftertaste.

Look up your interviewers and find out about them. Doing this in advance can be an eye-opening exercise. You might find out about their customer acquisition strategy which could lead to a ton of other interesting questions. If the company is a startup, do they plan on being acquired, or do they want to IPO? When you have a clear, well-thought question, it makes you sound professional, which again, is one of the things I listed as important.

If you can’t think of any questions to ask, then do you really want this job in the first place? If the interviewer has a personal website, go check it out, and if nothing else, you can ask them about the comic book they wrote and posted to their website.

But I’d advise:

  1. Ask the interview questions that you are generally interested about. Think about this before the interview because a really thoughtful question generally improves your candidacy quite a bit.
  2. What are you, the candidate, looking for in a company? What does this person, the interviewer, need to prove to you in order for you to take this job?
  3. Do these people have a good head on their shoulders like you do? It works both ways, you know.
  4. Does this look like a fun job? Do you even want a fun job?
  5. Who would you report to? Did you talk to them? Will you get a chance to during the interview process?
  6. Are you underrepresented? Like, are you replacing someone or filling a new role? How many others will be doing what you’re doing? What signs should other underrepresented people look out for? What signs would show you that this is a good environment for you?

Don't ask about money or benefits at this point; those things can (and likely should) be covered with a recruiter introduction call before you get to a person like me.

Conclusion

Interviewing, unlike programming, is not an exact science. You’re trying to prove that you are excited about the prospect of working with a company. You want to prove this to the interviewer and yourself. Hopefully, you want a job that is interesting. This guide isn’t a script to follow, but more of a few loose ideas to help you get into the mindset of the interviewer, with a few tips for other interviewers strung in there as well. Maybe I pointed out things you might not have known before.

Just remember that, in theory, interviewing should not be a scary process, but more of a find-some-buddies-to-work-with process.

The post Interviewing for a Technical Position Doesn’t Have to Be Scary appeared first on CSS-Tricks.



from CSS-Tricks http://bit.ly/2UGJZiP
via IFTTT

What Links to Target with Google's Disavow Tool - Whiteboard Friday

Thursday 25 April 2019

Corvid by Wix: Accelerated Development of Web Applications

Using Parcel as a Bundler for React Applications

You may already be familiar with webpack for asset management on projects. However, there’s another cool tool out there called Parcel, which is comparable to webpack in that it helps with hassle-free asset bundling. Where Parcel really shines is that it requires zero configuration to get up and running, where other bundlers often require writing a ton code just to get started. Plus, Parcel is super fast when it runs because it utilizes multicore processing where others work off of complex and heavy transforms.

So, in a nutshell, we’re looking at a number of features and benefits:

  • Code splitting using dynamic imports
  • Assets handling for any type of file, but of course for HTML, CSS and JavaScript
  • Hot Module Replacement to update elements without a page refresh during development
  • Mistakes in the code are highlighted when they are logged, making them easy to locate and correct
  • Environment variables to easily distinguish between local and production development
  • A "Production Mode" that speeds up the build by preventing unnecessary build steps

Hopefully, you’re starting to see good reasons for using Parcel. That’s not to say it should be used 100% or all the time but rather that there are good cases where it makes a lot of sense.

In this article, we’re going to see how to set up a React project using Parcel. While we’re at it, we’ll also check out an alternative for Create React App that we can use with Parcel to develop React applications. The goal here is see that there are other ways out there to work in React, using Parcel as an example.

Setting up a new project

OK, the first thing we need is a project folder to work locally. We can make a new folder and navigate to it directly from the command line:

mkdir csstricks-react-parcel && $_

Next, let’s get our obligatory package.json file in there. We can either make use of npm or Yarn by running one of the following:

## Using npm
npm init -y

## Using Yarn, which we'll continue with throughout the article
yarn init -y

This gives us a package.json file in our project folder containing the default configurations we need to work locally. Speaking of which, the parcel package can be installed globally, but for this tutorial, we’ll install it locally as a dev dependency.

We need Babel when working in React, so let’s get that going:

yarn add parcel-bundler babel-preset-env babel-preset-react --dev

Next, we install React and ReactDOM...

yarn add react react-dom

...then create a babel.rc file and add this to it:

{
  "presets": ["env", "react"]
}

Next, we create our base App component in a new index.js file. Here’s a quick one that simply returns a "Hello" heading:

import React from 'react'
import ReactDOM from 'react-dom'
class App extends React.Component {
  render() {
    return (
      <React.Fragment>
        <h2>Hello!</h2>
      </React.Fragment>
    )
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

We’ll need an HTML file where the App component will be mounted, so let’s create an index.html file inside the src directory. Again, here’s a pretty simple shell to work off of:

<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Parcel React Example</title>
  </head>
  <body>
    <div id="root"></div>
    <script src="./index.js"></script>
  </body>
</html>

We will make use of the Parcel package we installed earlier. For that to work, we need to edit the start script in package.json file so it looks like this:

"scripts": {
  "start": "NODE_ENV=development parcel src/index.html --open"
}

Finally, let’s go back to the command line and run yarn start. The application should start and open up a fresh browser window pointing at http://localhost:1234/.

Working with styles

Parcel ships with PostCSS out of the box but, if we wanted to work with something else, we can totally do that. For example, we can install node-sass to use Sass on the project:

yarn add --dev node-sass autoprefixer

We already have autoprefixer since it’s a PostCSS plugin, so we can configure that in the postcss block of package.json:

// ...
"postcss": {
  "modules": false,
  "plugins": {
    "autoprefixer": {
      "browsers": [">1%", "last 4 versions", "Firefox ESR", "not ie < 9"],
      "flexbox": "no-2009"
    }
  }
}

Setting up a production environment

We’re going to want to make sure our code and assets are compiled for production use, so let’s make sure we tell our build process where those will go. Again, in package-json:

"scripts": {
  "start": "NODE_ENV=development parcel src/index.html --open",
  "build": "NODE_ENV=production parcel build dist/index.html --public-url ./"
}

Running the yarn run build will now build the application for production and output it in the dist folder. There are some additional options we can add to refine things a little further if we’d like:

  • --out-dir directory-name: This is for using another directory for the production files instead of the default dist directory.
  • --no-minify: Minification is enabled by default, but we can disable with this command.
  • --no-cache: This allows us to disable filesystem cache.

💩 CRAP (Create React App Parcel)

Create React App Parcel (CRAP) is a package built by Shawn Swyz Wang to help quickly set up React applications for Parcel. According to the documentation, we can bootstrap any application by running this:

npx create-react-app-parcel my-app

That will create the files and directories we need to start working. Then, we can migrate over to the application folder and start the server.

cd my-app
yarn start

Parcel is all set up!

Parcel is worth exploring in your next React application. The fact that there's no required configuration and that the bundle time is super optimized makes Parcel worth considering on a future project. And, with more than 30,000 stars on GitHub, it looks like something that's getting some traction in the community.

Additional resources

  • Parcel Examples: Parcel examples using various tools and frameworks.
  • Awesome Parcel: A curated list of awesome Parcel resources, libraries, tools and boilerplates.

The source code for this tutorial is available on GitHub

The post Using Parcel as a Bundler for React Applications appeared first on CSS-Tricks.



from CSS-Tricks http://bit.ly/2IDT4aw
via IFTTT

Moving from Gulp to Parcel

Ben Frain just made some notes about the switch from Gulp to Parcel, a relatively new "web application bundler" which, from a quick look at things, is similar to webpack but without all the hassle of setting things up. One of the things I’ve always disliked about webpack is that you kinda have to teach it what CSS, HTML and JS are before making whatever modifications you want to those files. However, Parcel does a lot of the asset management and configuration stuff for us which is super neat — hence, Parcel claim that it requires “zero configuration.”

If you’d like to learn more about Parcel then there’s a great post by Indrek Lasn that details how to get started and even shows off a little bit about how Parcel is often faster than alternatives like webpack. We also just published a post by Kingsley Silas that explains how to use Parcel with React.

Direct Link to ArticlePermalink

The post Moving from Gulp to Parcel appeared first on CSS-Tricks.



from CSS-Tricks http://bit.ly/2IVsj0L
via IFTTT

Wednesday 24 April 2019

That Time I Tried Browsing the Web Without CSS

Preload, prefetch and other link tags

Ivan Akulov has collected a whole bunch of information and know-how on making things load a bit more quickly with preload and prefetch. That's great in and of itself, but he also points to something new to me – the as attribute:

<link rel="preload" href="/style.css" as="style" />

Supposedly, this helps browsers prioritize when to download assets and which assets to load.

My favorite part of this post is Ivan’s quick summary at the end which clearly defines what all these different tags can be used for:

<link rel="preload"> – when you’ll need a resource in a few seconds
<link rel="prefetch"> – when you’ll need a resource on a next page
<link rel="preconnect"> – when you know you’ll need a resource soon, but you don’t know its full url yet

Make sure to check out our own post on the matter of prefetching, preloading, and prebrowsing, too. Adding these things to our links can make significant performance improvements and so check it out to add more resources to your performance toolbox.

Direct Link to ArticlePermalink

The post Preload, prefetch and other link tags appeared first on CSS-Tricks.



from CSS-Tricks http://bit.ly/2GwlGPv
via IFTTT

Tuesday 23 April 2019

Who Are Design Systems For?

The Circle of a React Lifecycle

A React component goes through different phases as it lives in an application, though it might not be evident that anything is happening behind the scenes.

Those phases are:

  • mounting
  • updating
  • unmounting
  • error handling

There are methods in each of these phases that make it possible to perform specific actions on the component during that phase. For example, when fetching data from a network, you’d want to call the function that handles the API call in the componentDidMount() method, which is available during the mounting phase.

Knowing the different lifecycle methods is important in the development of React applications, because it allows us to trigger actions exactly when they’re needed without getting tangled up with others. We’re going to look at each lifecycle in this post, including the methods that are available to them and the types of scenarios we’d use them.

The Mounting Phase

Think of mounting as the initial phase of a component’s lifecycle. Before mounting occurs, a component has yet to exist — it’s merely a twinkle in the eyes of the DOM until mounting takes place and hooks the component up as part of the document.

There are plenty of methods we can leverage once a component is mounted: constructor() , render(), componentDidMount() and static getDerivedStateFromProps(). Each one is handy in it’s own right, so let’s look at them in that order.

constructor()

The constructor() method is expected when state is set directly on a component in order to bind methods together. Here is how it looks:

// Once the input component is mounting...
constructor(props) {
  // ...set some props on it...
  super(props);
  // ...which, in this case is a blank username...
  this.state = {
    username: ''
  };
  // ...and then bind with a method that handles a change to the input
  this.handleInputChange = this.handleInputChange.bind(this);
}

It is important to know that the constructor is the first method that gets called as the component is created. The component hasn’t rendered yet (that’s coming) but the DOM is aware of it and we can hook into it before it renders. As a result, this isn’t the place where we’d call setState() or introduce any side effects because, well, the component is still in the phase of being constructed!

I wrote up a tutorial on refs a little while back, and once thing I noted is that it’s possible to set up ref in the constructor when making use of React.createRef(). That’s legit because refs is used to change values without props or having to re-render the component with updates values:

constructor(props) {
  super(props);
  this.state = {
    username: ''
  };
  this.inputText = React.createRef();
}

render()

The render() method is where the markup for the component comes into view on the front end. Users can see it and access it at this point. If you’ve ever created a React component, then you’re already familiar with it — even if you didn’t realize it — because it’s required to spit out the markup.

class App extends React.Component {
  // When mounting is in progress, please render the following!
  render() {
    return (
      <div>
        <p>Hello World!</p>
      </div>
    )
  }
}

But that’s not all that render() is good for! It can also be used to render an array of components:

class App extends React.Component {
  render () {
    return []
      <h2>JavaScript Tools</h2>,
      <Frontend />,
      <Backend />
    ]
  }
}

...and even fragments of a component:

class App extends React.Component {
  render() {
    return (
      <React.Fragment>
        <p>Hello World!</p>
      </React.Fragment>
    )
  }
}

We can also use it to render components outside of the DOM hierarchy (a la React Portal):

// We're creating a portal that allows the component to travel around the DOM
class Portal extends React.Component {
  // First, we're creating a div element
  constructor() {
    super();
    this.el = document.createElement("div");
  }
  
  // Once it mounts, let's append the component's children
  componentDidMount = () => {
    portalRoot.appendChild(this.el);
  };
  
  // If the component is removed from the DOM, then we'll remove the children, too
  componentWillUnmount = () => {
    portalRoot.removeChild(this.el);
  };
  
  // Ah, now we can render the component and its children where we want
  render() {
    const { children } = this.props;
    return ReactDOM.createPortal(children, this.el);
  }
}

And, of course, render() can — ahem — render numbers and strings...

class App extends React.Component {
  render () {
    return "Hello World!"
  }
}

...as well as null or Boolean values:

class App extends React.Component {
  render () {
    return null
  }
}

componentDidMount()

Does the componentDidMount() name give away what it means? This method gets called after the component is mounted (i.e. hooked to the DOM). In another tutorial I wrote up on fetching data in React, this is where you want to make a request to obtain data from an API.

We can have your fetch method:

fetchUsers() {
  fetch(`https://jsonplaceholder.typicode.com/users`)
    .then(response => response.json())
    .then(data =>
      this.setState({
        users: data,
        isLoading: false,
      })
    )
  .catch(error => this.setState({ error, isLoading: false }));
}

Then call the method in componentDidMount() hook:

componentDidMount() {
  this.fetchUsers();
}

We can also add event listeners:

componentDidMount() {
  el.addEventListener()
}

Neat, right?

static getDerivedStateFromProps()

It’s kind of a long-winded name, but static getDerivedStateFromProps() isn’t as complicated as it sounds. It’s called before the render() method during the mounting phase, and before the update phase. It returns either an object to update the state of a component, or null when there’s nothing to update.

To understand how it works, let’s implement a counter component which will have a certain value for its counter state. This state will only update when the value of maxCount is higher. maxCount will be passed from the parent component.

Here’s the parent component:

class App extends React.Component {
  constructor(props) {
    super(props)
    
    this.textInput = React.createRef();
    this.state = {
      value: 0
    }
  }
  
  handleIncrement = e => {
    e.preventDefault();
    this.setState({ value: this.state.value + 1 })
  };

  handleDecrement = e => {
    e.preventDefault();
    this.setState({ value: this.state.value - 1 })
  };

  render() {
    return (
      <React.Fragment>
        <section className="section">
          <p>Max count: { this.state.value }</p>
          <button
            onClick={this.handleIncrement}
            class="button is-grey">+</button>
          <button
            onClick={this.handleDecrement}
            class="button is-dark">-</button>          
        </section>
        <section className="section">
          <Counter maxCount={this.state.value} />
        </section>
      </React.Fragment>
    )
  }
}

We have a button used to increase the value of maxCount, which we pass to the Counter component.

class Counter extends React.Component {
  state={
    counter: 5
  }

  static getDerivedStateFromProps(nextProps, prevState) {
    if (prevState.counter < nextProps.maxCount) {
      return {
        counter: nextProps.maxCount
      };
    } 
    return null;
  }

  render() {
    return (
      <div className="box">
        <p>Count: {this.state.counter}</p>
      </div>
    )
  }
}

In the Counter component, we check to see if counter is less than maxCount. If it is, we set counter to the value of maxCount. Otherwise, we do nothing.

You can play around with the following Pen below to see how that works on the front end:

See the Pen
getDerivedStateFromProps
by Kingsley Silas Chijioke (@kinsomicrote)
on CodePen.


The Updating Phase

The updating phase occurs when a component when a component’s props or state changes. Like mounting, updating has its own set of available methods, which we’ll look at next. That said, it’s worth noting that both render() and getDerivedStateFromProps() also get triggered in this phase.

shouldComponentUpdate()

When the state or props of a component changes, we can make use of the shouldComponentUpdate() method to control whether the component should update or not. This method is called before rendering occurs and when state and props are being received. The default behavior is true. To re-render every time the state or props change, we’d do something like this:

shouldComponentUpdate(nextProps, nextState) {
  return this.state.value !== nextState.value;
}

When false is returned, the component does not update and, instead, the render() method is called to display the component.

getSnapshotBeforeUpdate()

One thing we can do is capture the state of a component at a moment in time, and that’s what getSnapshotBeforeUpdate() is designed to do. It’s called after render() but before any new changes are committed to the DOM. The returned value gets passed as a third parameter to componentDidUpdate().

It takes the previous state and props as parameters:

getSnapshotBeforeUpdate(prevProps, prevState) {
  // ...
}

Use cases for this method are kinda few and far between, at least in my experience. It is one of those lifecycle methods you may not find yourself reaching for very often.

componentDidUpdate()

Add componentDidUpdate() to the list of methods where the name sort of says it all. If the component updates, then we can hook into it at that time using this method and pass it previous props and state of the component.

componentDidUpdate(prevProps, prevState) {
  if (prevState.counter !== this.state.counter) {
    // ...
  }
}

If you ever make use of getSnapshotBeforeUpdate(), you can also pass the returned value as a parameter to componentDidUpdate():

componentDidUpdate(prevProps, prevState, snapshot) {
  if (prevState.counter !== this.state.counter) {
    // ....
  }
}

The Unmounting Phase

We’re pretty much looking at the inverse of the mounting phase here. As you might expect, unmounting occurs when a component is wiped out of the DOM and no longer available.

We only have one method in here: componentWillUnmount()

This gets called before a component is unmounted and destroyed. This is where we would want to carry out any necessary clean up after the component takes a hike, like removing event listeners that may have been added in componentDidMount(), or clearing subscriptions.

// Remove event listener 
componentWillUnmount() {
  el.removeEventListener()
}

The Error Handling Phase

Things can go wrong in a component and that can leave us with errors. We’ve had error boundary around for a while to help with this. This error boundary component makes use of some methods to help us handle the errors we could encounter.

getDerivedStateFromError()

We use getDerivedStateFromError() to catch any errors thrown from a descendant component, which we then use to update the state of the component.

class ErrorBoundary extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      hasError: false
    };
  }

  static getDerivedStateFromError(error) {
    return { hasError: true };
  }
  
  render() {
    if (this.state.hasError) {
      return (
        <h1>Oops, something went wrong :(</h1>
      );
    }

    return this.props.children;
  }
}

In this example, the ErrorBoundary component will display “Oops, something went wrong” when an error is thrown from a child component. We have a lot more info on this method in a wrap up on goodies that were released in React 16.6.0.

componentDidCatch()

While getDerivedStateFromError() is suited for updating the state of the component in cases where where side effects, like error logging, take place, we ought to make use of componentDidCatch() because it is called during the commit phase, when the DOM has been updated.

componentDidCatch(error, info) {
  // Log error to service
}

Both getDerivedStateFromError() and componentDidCatch() can be used in the ErrorBoundary component:

class ErrorBoundary extends React.Component {
  
constructor(props) {
  super(props);
  this.state = {
    hasError: false
  };
}

  static getDerivedStateFromError(error) {
    return { hasError: true };
  }

  componentDidCatch(error, info) {
    // Log error to service
  }
  
  render() {
    if (this.state.hasError) {
      return (
        <h1>Oops, something went wrong :(</h1>
      );
    }

    return this.props.children;
  }
}

And that’s the lifecycle of a React component!

There’s something neat about knowing how a React component interacts with the DOM. It’s easy to think some “magic” happens and then something appears on a page. But the lifecycle of a React component shows that there’s order to the madness and it’s designed to give us a great deal of control to make things happen from the time the component hits the DOM to the time it goes away.

We covered a lot of ground in a relatively short amount of space, but hopefully this gives you a good idea of not only how React handles components, but what sort of capabilities we have at various stages of that handling. Feel free to leave any questions at all if anything we covered here is unclear and I’d be happy to help as best I can!

The post The Circle of a React Lifecycle appeared first on CSS-Tricks.



from CSS-Tricks http://bit.ly/2UPfb4q
via IFTTT

Passkeys: What the Heck and Why?

These things called  passkeys  sure are making the rounds these days. They were a main attraction at  W3C TPAC 2022 , gained support in  Saf...