Bad CSS in JS

I tried to understand the argument made for styled components vs. ‘traditional’ CSS. But when reviewing these arguments I found out that they typically use bad code as proof for their point.

See e.g. the following SCSS code:

$blue = #5DBCD2;

@mixin button-styles($bg-color, $color) {
  background: $bg-color;
  color: $color;
  border: none;
  border-radius: 0.20em;
  &:hover{
      background: darken($bg-color, 6%);
      cursor: pointer;
  }
}

.button {
  @include button-styles(#ddd, black)
}

.button--primary {
  @include button-styles($blue, white)
}

To pair with a simple component along the lines of:

const Buttons = props => (
  <>
    <button className="button">Default</button>
    <button className="button--primary">Primary</button>
  </>
)
export default Buttons

The suggested alternative is:

import themeVars from "myTheme"
import styled from "styled-components"
import { darken } from "polished"

const Button = styled.button`
  background: ${({ background }) => background || "#ddd"};
  color: ${({ color }) => color || "black"};
  border: none;
  border-radius: 0.25em;
  :hover {
    background: ${({ background }) => darken(0.05, background || "#ddd")};
  }
`

const Buttons = props => {
  const { blue } = props.theme.colors;
  return (
    <>
      <Button>Default</Button>
      <Button background={blue} color={"white"}>Primary</Button>
    </>
  )
}
export default withTheme(Buttons)

You might think this is better when you’re used to writing the earlier mentioned SCSS/SASS.

Learn CSS again.

With good ol’ CSS you’d write:

.button {
  background: #ddd;
  color: #000;
  border: none;
  border-radius: 0.25em;
  &:hover{
      background: #ccc; /*estimation*/
      /* cursor: pointer; <- also don't: another discussion */
  }
}

.button--primary {
  background: #5DBCD2;
  color: #fff;
  &:hover{
      background: #4DACC2; /*estimation*/
  }
}

The HTML would be:

<button class="button"></button>
<button class="button button--primary”></button>

In BEM, what the original example seemed to be using, modifiers modify, they are not the style itself as well. Please, front-end devs: Let’s not (programatically) over duplicate & complicate things.

Note, in contrast to some of the pure CSS folks, I’m not anti-SCSS. I actually do use SCSS; to store the typical theme variables for margins, colours etc. I even use an occasional function to darken something or calculate some ratio’s (typically at settings level). Even an occasional include to replicate an almost similar border style for totally unrelated objects. But never to overcomplicate things.

Lazy loading the lazy way

Large pages with many images make pages heavy to load.

Below is a simple, lazy, technique I applied in a collection management tool where its users wanted to browse over 10.000 images without scroll-hijacking or pagination. Sure, only the HTML weight several MB’s at once, but for this particular application used by professionals it is worth the weight. But performance was too heavily affected by downloading all these separate images.

So let’s have a look how I solved this.

What does the code below do?

<figure class="image">         
  <noscript data-lazy="lazy-load">
    <img class="nonlinked_show" decoding="async" src="/uploads/images/1540215129.jpg" alt="tree in field" />         
  </noscript>
</figure>

You rightly guessed that it won’t display any image to say ~95% of the users. The 5% who have disabled Javascript however, will see it.

The 95% who do have Javascript can enjoy the image simply by moving the img tag out of the noscript tag using a bit of JavaScript:

ELEMENTS_QUERY = "noscript[data-lazy=\"lazy-load\"]"

decode_entities = (encodedString)->
   # required for IE and Safari
   textArea = document.createElement('textarea')
   textArea.innerHTML = encodedString
   textArea.value

lazy_load_image_in_noscript_wrapper = (noscript_tag)->
   fragment = noscript_tag.innerHTML
   parent = noscript_tag.parentElement
   parent.innerHTML = decode_entities(fragment)

lazy_load_images = ->
  noscript_wrapped_images = document.querySelectorAll(ELEMENTS_QUERY)
  noscript_wrapped_images.forEach(lazy_load_image_in_noscript_wrapper)

document.addEventListener "ready", ->
   lazy_load_images()

Yeah, I don’t enjoy typing ;’s, so it’s Coffeescript here. It also reads more like pseudocode 🙂 You can convert it here.

But this ain’t lazy loading yet. It brings back the images though. And next up is actually making the images load lazily.

I promised to keep this lazy. So I’m only going to implement lazy loading (which I consider an progressive improvement over traditional loading) for newer browsers that actually support the IntersectionObserver. Currently supported by almost 70% of the browsers (including Firefox, Chrome, Edge), soon close to 80% when a new version of Safari is being released.

Here is the rewritten lazy_load_images()-method:

lazy_load_images = ->   
  noscript_wrapped_images = document.querySelectorAll(ELEMENTS_QUERY) 
  supportsIntersectionObserver = typeof IntersectionObserver == "function"   
  if supportsIntersectionObserver
     intersectionObsOptions =
       root_margin: "100px"
     intersectionObserver = new IntersectionObserver((entries)->
       entries.forEach(process_intersection_observer_entry)
     , intersectionObsOptions)
     noscript_wrapped_images.forEach((e)->intersectionObserver.observe(e.parentElement))
   else
     noscript_wrapped_images.forEach(lazy_load_image_in_noscript_wrapper

And there you have it. Lazy lazy loading. Make sure that you prevent reflows though. Without proper styling your page may have to be re-rendered all the way down when a single image is triggered for loading. So make sure there is an relatively positioned container for your images which removes the position of the images from the document flow.

Bonus points: how to make it work for print:

show_all_images = ->
   noscript_wrapped_images = document.querySelectorAll(ELEMENTS_QUERY)
   noscript_wrapped_images.forEach(lazy_load_image_in_noscript_wrapper)

# handle pritning of images: https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeprint

window.addEventListener "beforeprint", ->
   show_all_images()

mediaQueryList = window.matchMedia('print');
mediaQueryList.addListener (mql)->
   if mql.matches
     show_all_images()

I hope you enjoyed this. If so, sign-up for my mailinglist to get the latest in your inbox!