DEV Community

Cover image for JavaScript Should Be Your Last Resort
Olavi Haapala
Olavi Haapala

Posted on • Originally published at olavihaapala.fi on

JavaScript Should Be Your Last Resort

JS Is Your Hammer

When working on modern frontend web development, using your favorite framework of choice, it can be sometimes tempting to solve all the problems with JavaScript. Sometimes this happens unconsciously as JS is what you mostly use in your day-to-day development work.

This is similar to the situation described by Abraham Maslow in 1966:

I suppose it is tempting, if the only tool you have is a hammer, to treat everything as if it were a nail.

Wikipedia: Law of the instrument

Photo of a hammer about to hit some nails

Photo by Fausto Marqués on Unsplash

Note: In this blog post, I’m only talking about JS even though I’m mostly using TS in my projects – it ends up as JS after compilation anyways.

What to Take into Account When Implementing UI

This mindset of using JS for everything causes unnecessary processing that needs to be run on your end users’ devices as client-side JS. All the JS resources on a website need to be downloaded, parsed and executed by the web browser. This is quite often the cause of slow and unresponsive websites on low-end mobile devices or slow network speeds.

How You Should Be Thinking Instead:

  1. Can this be done in HTML?
  2. If not, can I solve it with HTML + CSS?
  3. And if nothing else works, the solution probably requires a minimal amount of JS in addition to HTML and CSS

This way of thinking is not about what is easiest for you as a developer. You may be a JavaScript focused frontend developer, and solving most of your problems with it feels natural for you. However, you should be thinking about your end users. Client-side JS is the single biggest problem when it comes to web performance. You can read some of my thoughts on web performance from my other blog posts. You can find some links at the bottom of this blog post on my personal blog.

1. Can This Be Done in HTML?

Plan and implement the basic structure and semantics of the feature in plain HTML without any extra styles and using native HTML elements and functionality. If some additional styling or features are needed, go to step 2.

2. Try to Solve It with HTML + CSS

Use CSS to apply the additional styling or animation that is required, still keeping the semantics and accessibility in my mind. If some additional interactivity is required in the particular piece of UI you are building, go to step 3.

3. Use HTML + CSS + JS

Add the minimum amount of JS required to fulfill the requirements. Keep in mind that something that can be solved without JS should probably be solved without JS.

When you’re done, show your code to your colleagues and let them review it. Perhaps there is still something unnecessary parts in your code, that could be solved without having a client-side JS cost for your users.

Simple Example

This problem applies to almost anything in web frontend development, but here is a simple practical example that should help me prove my point.

Imagine you are working on a React project, and you are working on a feature that has some UI parts that should only become visible after a certain delay, let’s say after 2s.

Using React Hooks

If you are used to solving your problems with React and Hooks, your initial solution could look something like this:

const [thingVisible, setThingVisible] = useState(false);

useEffect(() => {
  const timeoutId = setTimeout(() => {
    setThingVisible(true);
  }, 2000);

  return function cleanup() {
    clearTimeout(timeoutId);
  };
}, []);

return thingVisible ? <section>Here's a thing for you!</section> : null;

Enter fullscreen mode Exit fullscreen mode

This is fine and works. Probably you notice no difference in performance either on your hyper powerful developer machine. And probably, there is no real performance issue in this case. But imagine if these pile up and suddenly you would have tens or hundreds of similar unnecessary JS computations to be run on the client-side or some larger and longer executions that are taking place.

Using HTML + CSS Animation

Using CSS, you can animate content to appear on the page with a delay using CSS animations and animation-delay. This is supported by all browsers and could even have a better end user experience as you could fade the content in or use any other ways of making the content appear more smoothly.

The HTML:

<section class="fade-in">Here's a thing for you!</section>

Enter fullscreen mode Exit fullscreen mode

The CSS:

.fade-in {
  opacity: 0;
  animation: fadeIn 2s;
  animation-delay: 2s;
  animation-fill-mode: forwards;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

Enter fullscreen mode Exit fullscreen mode

Don’t Use CSS for What You Can Do with HTML

Similarly, don’t do something with CSS that you could and should be doing in HTML.

An extreme example of this was that we had accidentally been using margins to separate two words from each other, instead of using a space in between the words!

This was obviously not a good idea from at least the following perspectives:

  • It might not follow the font size, letter spacing etc.
  • It is not needed, waste of effort and processing
  • If someone would need to copy the text, there would be no space in between the words

Frontend Development Is Not Easy

Web frontend development is not an easy topic to master. It is something you can get started with quite rapidly, but mastering it requires some level of experience and understanding the whole picture in order to be able to solve the right problems on the right level using the right tools. Solving something on the frontend has many levels and details baked in it.

Additionally, you’ll need to understand when a problem should be solved on the backend instead of the frontend for various reasons such as performance, usability or maintainability among others.

However, keep in mind that sometimes you don’t need to try to reach for a perfect solution and something that works might be good enough to be shipped to production and to be used by your end users.

Oldest comments (120)

Collapse
 
grahamthedev profile image
GrahamTheDev • Edited

I get oh so happy seeing posts like this - have a ❤ and 🦄

This problem will never go away but I really hope you get through to one person, React, Angular, Vue.js are fantastic...for very complex interfaces, if you are building a mostly static page please please just use HTML, CSS and a sprinkling of vanilla JS, your load performance and conversion rates will thank you.

Collapse
 
olpeh profile image
Olavi Haapala

Thanks ☺️

Collapse
 
arvindsridharan profile image
arvindsridharan

Awesome post.

Collapse
 
oenonono profile image
Junk

Great job

Collapse
 
ronca85 profile image
ronca85

i see job posts saying react is a must-know thing now. meanwhile i almost never see html or css listed in job listings, as if they don't matter. they do matter, and they're more important than js. understand the basics really well first. people skip all this noob basic stuff and then i end up with people that know a little react but everything on the page is a div and the task on the table is make this website 100% accessible. aaaaaaaaaaaaaaaaaaa!!!!!!!!!

Collapse
 
olpeh profile image
Olavi Haapala

I totally agree! And sadly know what you're talking about 🤷‍♂️

Collapse
 
raddevus profile image
raddevus • Edited

I am so glad to hear someone say that. I think the same thing. Learn the foundations first. Learn what each thing was created for HTML (document structure) CSS (document styling) JavaScript (document automation). That's why I start out with the foundational basics in my book, Learn HTML, CSS & JavaScript : Launch Your Dev Career. If your interested in the book reply to me and I'll provide a link for a free copy.

Great post and reply. Thanks

Collapse
 
fitzedin profile image
fitzedin

heard you're giving away a book ..

Thread Thread
 
raddevus profile image
raddevus

I am and I'm glad to provide a copy to you. You have to follow me here on Dev (i've already followed you) so I can DM you the link. When you follow me, I'll send you a link to the PDF download.

Collapse
 
henwheat profile image
Henwheat

Heard the same that fitzedin, actually I'm trying to teach myself the basics from front end, but with only English content, because here in Brazil things are a little bit difficult to find hahahah. Would love to have your book!

Thread Thread
 
raddevus profile image
raddevus

I am and I'm glad to provide a copy to you. You have to follow me here on Dev (i've already followed you) so I can DM you the link. When you follow me, I'll send you a link to the PDF download.

Thread Thread
 
adegbengaagoro profile image
Agoro, Adegbenga. B

Hi, interested in your book

Thread Thread
 
raddevus profile image
raddevus

I sent you the link in Chat. Thanks

Collapse
 
nhlanhlahlasa profile image
Ntando

Hi, I'm interested in your book. May I please have a copy? 🤗

Thread Thread
 
raddevus profile image
raddevus

Please follow me here on dev.to and I will Chat you and send you the link to the free book. thanks

Thread Thread
 
ntjedge profile image
NTJ

Hi, I have started learning HTML and CSS, just talking baby steps. Would love to get a copy of your book. I am following you already. Thanks :)

Thread Thread
 
raddevus profile image
raddevus

I sent the link to you in Chat. 😊

Collapse
 
denizshelby profile image
Deniz_shelby

Very intrested!

Thread Thread
 
raddevus profile image
raddevus

Please follow me here on Dev.to so I can Chat you and send you the link to the free book. thanks

Collapse
 
flyinpanda69 profile image
flyinPanda69

Hello raddevus,
I would love to read the book and understand the concept. Could you please provide the link. rarockin002@gmail.com is my email.
Thank you.

Thread Thread
 
raddevus profile image
raddevus

If you will please follow me here on dev.to I will send link via chat

Collapse
 
smartolade profile image
Egbowon Daniel

I just started learning html and CAD. I would love a copy of the book

Thread Thread
 
smartolade profile image
Egbowon Daniel

I meant CSS.

Thread Thread
 
raddevus profile image
raddevus

Sure, please just follow me here on Dev.to and I will send you the link. I've already followed you, but we have to follow each other to send Chat / DMs

Collapse
 
niklasvatn profile image
Niklas Vatn • Edited

Hi, I would very much appreciate a copy :)

Thread Thread
 
raddevus profile image
raddevus

Please follow me here on Dev.to and I can send book link via Chat. thx

Thread Thread
 
raddevus profile image
raddevus

I sent it to you in Chat. Thanks

Collapse
 
neoplatonist profile image
Neoplatonist

Hey, I am interested in your book as well! Thanks in advance!

Thread Thread
 
raddevus profile image
raddevus

Please follow me here on dev.to and I'll send you a link to the PDF book in Chat. Thanks

Collapse
 
amack112 profile image
amack112

Thanks so much for offering the book, would love to get a copy amackp@gmail.com cheers!!

Thread Thread
 
raddevus profile image
raddevus

Please follow me so I can Chat you and send you the link to my book. thanks

Collapse
 
tekmom profile image
Catherine Shiver

I would like a copy, as well, please. Thank you

Thread Thread
 
raddevus profile image
raddevus

Please follow me here on Dev.to so I can Chat you and send you a link to my book. thanks

Thread Thread
 
raddevus profile image
raddevus

I sent you a copy in Chat.

Collapse
 
fofomalo profile image
Florent Malo

J'ai personnellement mis du temps à comprendre le CSS, plus quand j'ai abordé le Sass holalala, l'émerveillement et aussi toute la beauté d'un langage.
Et j'avoue que jusqu'à présent c'est une toujours une découverte.
Intéressé de découvrir votre livre sur ces sujets.
Merci d'avance

Thread Thread
 
raddevus profile image
raddevus

Thanks for your interest in my book. Please follow me here on Dev.to so I can Chat and send you the link to your free copy. Thanks

Thread Thread
 
fofomalo profile image
Florent Malo

\o/ ça serait avec joie

Collapse
 
jam52 profile image
Jamie Sajdak

I did exactly this, now I'm going back and learning the basics properly! I'd love a link to the book! Thank you :)

Thread Thread
 
raddevus profile image
raddevus

I've followed you. Please just follow me here at dev.to so I can Chat (DM) and send you the link. thanks

Collapse
 
dhegyaino16 profile image
McCall

Hello pls I need a copy of your book

Thread Thread
 
raddevus profile image
raddevus

I sent you the link in Chat. Thanks

Collapse
 
joblessnigga profile image
Alakowe

Hi Raddevus,
I am a newbie webdev, I'm interested in book.
Thanks.

Thread Thread
 
raddevus profile image
raddevus

I sent you the link in Chat. 😊

Thread Thread
 
raddevus profile image
raddevus

I sent you the book in Chat.

 
raddevus profile image
raddevus

I sent you the book in chat.

Collapse
 
kalestric profile image
d

Hi, I would love a copy of your book, thanks!

Thread Thread
 
raddevus profile image
raddevus

Glad to provide the link to the book. Please follow me here on dev.to (I'm following you) then I can Chat you here and send you the link. It's just the way dev.to works. We both have to follow each other. thanks

Thread Thread
 
kalestric profile image
d

Following!

Thread Thread
 
raddevus profile image
raddevus

I sent you the book in Chat.

Collapse
 
otinomz profile image
Exhale Words

Interested in your book. Just followed you also. May I have a free copy please

Thread Thread
 
raddevus profile image
raddevus

I sent you the link in chat.

Collapse
 
toanoop profile image
Anoop Sivadas

Can I please get a copy

Thread Thread
 
raddevus profile image
raddevus

Happy to send you the link, but please follow me here on Dev.to so I can send you the link in Chat. Thanks

Thread Thread
 
toanoop profile image
Anoop Sivadas

Yes just did

Collapse
 
joomlaserbia profile image
Momir Despotović

Please send a copy

Thread Thread
 
raddevus profile image
raddevus

Please follow me here on Dev.to so I can send you a DM in Chat. Then I'll send you the link to the free PDF. thanks

Thread Thread
 
raddevus profile image
raddevus

I sent you the link in Chat.

Collapse
 
jacobandersen profile image
Jacob Andersen

i would love a copy of your book to complement my javascript studies. i am very much a subscriber to the bite size lessons approach!

Thread Thread
 
raddevus profile image
raddevus

I sent you a copy in Chat. 😊

Collapse
 
dagoks profile image
Dayo

Hello, I am interested in your book and would love to get a link as well, thank you.

Thread Thread
 
raddevus profile image
raddevus

I sent the link in Chat.

Collapse
 
kofsaku profile image
Kofsaku

Hi! I am new here but I feel the needs of more understanding of front end recently. I am really interested in your book.

Collapse
 
kevinpfleming profile image
Kevin Patrick Fleming

Would love a link to your book and thanks in advance!

Collapse
 
carlbaiden66 profile image
Jibbs Carlington

Hey can I get the book please. I've followed you

Thread Thread
 
raddevus profile image
raddevus

I sent you a copy in Chat.

Collapse
 
sidcraftscode profile image
sid

Would love to have your book thanks!

Thread Thread
 
raddevus profile image
raddevus

Thanks, I sent you the link in Chat.

Collapse
 
a0323022 profile image
Trey

Hi, I'm just getting started in trying to self learn front end dev. Is it too late to get a copy of your book? Is it good as a beginner resource? Thank you so much

Collapse
 
yaser profile image
Yaser Al-Najjar

Well, this might indicate to a larger problem in the industry... recruiters who have no idea about the tech basics, but the fancy tech names (React, Docker, AWS... you name it).

This problem might be worth shedding light on.

Collapse
 
btlm profile image
btlm

Very important comment. It's a kind of plague nowadays.

Collapse
 
fofomalo profile image
Florent Malo

Absolument d'accord, maîtriser du html et du CSS la base.

Collapse
 
dskaiser82 profile image
Daniel Kaiser

Blasphemy!! Get 'em!!!

Collapse
 
fduteysimfinity profile image
fdutey-simfinity

It's because we assume that it's such a basic that you can't do react without html and a minimum of css

Collapse
 
tccodez profile image
Tim Carey

Part of the reason is the clever programmer react videos use all divs LOL it sucks because I got sucked into that as a n00b. It's tough being a beginner learning on your own. There is a lot of information out there but a lot of it is not so good information. When you don't know anything, you can't tell what is good or bad. Especially when the code works, it's even HARDER to tell what code is good and what code is garbage.

Collapse
 
michaelpierre profile image
Michael Pierre

I love this approach and will try to implement it moving forward!

Collapse
 
bclonan profile image
Bradley Morgan Clonan

While agree many solutions can be solved with html/css rather than js. At the end of the day, the benefit of using js over html/css is js is far more reusable. More often than not tech companies aren't just building one product, and they aren't tied into just one style guide. You can tell Js to do something and it will do it regardless of legacy code bases, poorly structured style files etc.

Collapse
 
ojrask profile image
Otto Rask

I don't get your point. HTML is way more resilient than JS and it keeps doing what you tell it to do even when you partly get it wrong?

Reusability is good with just HTML and CSS as well, or are you talking about installing shit with a package manager?

Collapse
 
bclonan profile image
Bradley Morgan Clonan • Edited

When your starting with a fresh or very well defined code base sure, you can federated your class names, your animations, your style libraries etc. Though that's rarely the case, what I am saying is with js if you write a function to do something like apply (for simplicities sake) display:none to a Dom element on the fly you can carry that function with you to every project, no worries about conflicts, and if there is a conflict like repeated function names etc it's very easyto debug, more often than not the browser will immediately tell you. If you create a class named .hidden { display:none;} and you hop into a legacy code base, or one that's using x style framework trying to use your little utility class and it doesn't work your going to spend far more time digging to find the conflicting class name. Of course this is a very simple and mostly impractical example but apply it to far more involved things. My comment primarily applies to css, html is what it is whether it's written in jsx, handlebars, dynamically loaded in through a api call whatever. The unfortunate Dom is, the unfortunate dom.

Thread Thread
 
ojrask profile image
Otto Rask

What would happen if you took your JS display:none function to a legacy project with a x style JS framework that has certain kinds of tools to style DOM elements? You seem to know exactly what happens with CSS in this case so I expect you to know the answer to JS things as well.

if there is a conflict like repeated function names etc it's very easyto debug, more often than not the browser will immediately tell you

How about you press F12 right now, open the console, and declare two JS functions with the same name into the window. Let me know what the error message says.

Thread Thread
 
bclonan profile image
Bradley Morgan Clonan • Edited

So I tried it, and JS is alot easer to debug than css.

<!DOCTYPE html>
<html>
<style>

#pageHeading {
display : none;
}


#pageHeading {
display : block;
}
</style>
<body>

<h1 id="pageHeading">Hide Me Now</h1>

<button onclick="myHideDomElementFunction('#pageHeading')">Try it</button>

<script>

const myHideDomElementFunction = targetElement => document.querySelector(targetElement).style.display = "none";

const myHideDomElementFunction = targetElement => document.querySelector(targetElement).style.display = "none";

</script>

</body>
</html>
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
ojrask profile image
Otto Rask

Easier how? I am not certain how that example should be read or executed to validate your point?

Collapse
 
mzaini30 profile image
Zen

I got inspiration from this post and I'll do my projects with only PHP. But, interactivity is better with Svelte than PHP (without JavaScript)

Collapse
 
olpeh profile image
Olavi Haapala

Nice to hear 🎉

Collapse
 
festuquet profile image
Eduard Vidal i Tulsà freedom 4 Julian Assange

I just use js only for know data about client screen. Some one tell me I'm very legacy programmer. I'm glad to be not the only one that don't trust in client cpu.

Collapse
 
bergamin profile image
Guilherme Taffarel Bergamin

I have been a backend developer for most of my career. That suddenly changed 2 years ago when a lack of workforce with experience on Angular in my company hit hard (the details are unimportant) and I was from one day to the other assigned a front-end role.

My first months on it were a bit of a pain, having to learn HTML, CSS, TS and Angular on the go without a tutor, but I got the hang of it and now I'm mainly working with Angular here on several projects. One thing became very clear to me after I finished that first project. I made a lot more stuff in TS than I should have.

Now I understand much better the role of each layer and I know the "vocabulary" and "grammar" of HTML and CSS a lot more. Beforehand I used to despise TypeScript after such a long time working with backend only, but now I see it's flaws are actually inherited from JS, and TS is actually a wonderful tool if well used. It's easier to work with than Java in some aspects and it reminds me of Kotlin sometimes (even though I would still prefer Kotlin over Java or TS)

HTML in Angular is a lot more easy to deal with and SCSS helps a lot with those variables. I still struggle with CSS though. It has a lot of hidden peculiarities and a little slip makes the whole page to crumble sometimes...

Anyway, what I was saying is that when you realise the role of each layer, all of what this article says becomes second nature.

Collapse
 
olpeh profile image
Olavi Haapala

Thanks for the comment! Perhaps you could write a blog post about your experience?

Collapse
 
bergamin profile image
Guilherme Taffarel Bergamin

Thanks for the suggestion, I may think about it. BTW, about the client-side PC not being as fast as your dev PC, I overcome that by using an old Android phone that used to be a entry/mid-range phone 5 years ago with a tiny screen to test my Angular apps. A Motorola Moto E2.

With it I can test both performance issues and UI on a small screen (DevTools mobile mode doesn't give the real feel. Also, I had to tackle some problems caused by the address bar on mobile, which isn't present in DevTools mobile mode).

Collapse
 
godwin_france profile image
Saharan-sub

Great piece

Collapse
 
king11 profile image
Lakshya Singh

I also started using Frontend Frameworks because it seems so cool and everyone is doing it. I later realized that I missed on so many cool parts of HTML5 and CSS3 that are more performant and easy to work on be it the use of semantic HTML, Grids and Flex box in CSS or even selectors everything is important its not just JS.

Collapse
 
olpeh profile image
Olavi Haapala • Edited

Yeah, and one thing that comes to my mind is simple stuff like numbered list. Some people might render a list as <ul> and add the index +1 as the number on the left side of the item because they might not know about <ol> and everything you can do with CSS.

Also CSS counters, pseudo content etc. etc.

Collapse
 
mccurcio profile image
Matt Curcio

Really excellent idea(s). This is so true with so many things.
Don't over-complicate things.

Collapse
 
crimsonmed profile image
Médéric Burlet

YES YES YES YES AND YES
The amount of people I met that call themselves web-developers because they can make a react component but then don't even know that you can do animations in CSS or even the difference between absolute and relative positions.

Collapse
 
imsuvesh profile image
Suvesh K

Read that Hammer quote -> Here You Go ❤️

Collapse
 
zenwork profile image
Florian Hehlen

Reading the first sentence I thought this was going to be a framework v. vanilla article and was ready to be critical! Having read through I couldn't agree more. But I would go further and say that you don't have to use React if some simple vanilla JS will do.

Collapse
 
olpeh profile image
Olavi Haapala

Thanks! Yeah, I agree. But this was based on my current project(s) where React is used, and that won't change in the near future. It's easier to change how you use the framework instead of rewriting everything. Also, it's good to keep in mind the actual impact on the end users.
There are even solutions that use React on the server, but have no runtime JS – so the end users don't get punished for your choice of framework.

Collapse
 
zenwork profile image
Florian Hehlen

I have had to do a lot of React lately. I think there is also some arguments to be made about how much you use it. For example there is a tendency to break everything down into micro components which gets excessive. I think the functional and stateless dogma leads often to heavy to execute and unreadable code.... which is funny because that is exactly what React wants to solve.

Thread Thread
 
olpeh profile image
Olavi Haapala

I think this is also a problem that is not React specific. This problem will occur in every project that grows large enough.

Thread Thread
 
zenwork profile image
Florian Hehlen

For sure! I have seen this in other languages and with all sorts of frameworks over the years. It is very tempting as a developer to look at any DX improvement as an improvement for the universe.

Collapse
 
erebos-manannan profile image
Erebos Manannán

The worst thing is how often JavaScript developers reinvent the wheel and break accessibility, common shortcuts such as Ctrl+Clicking or middle-clicking on links to open things in a new tab because the navigation is implemented as onclick handlers instead of <a href="">, or really the worst common issue is making your custom dropdown which does not support the same keyboard selection as a normal dropdown does. Why? So it looks marginally better?

Collapse
 
olpeh profile image
Olavi Haapala

I generally think there's nothing wrong with the browser default styles for input elements. Why can't we often stick with those and avoid wasting time re-inventing the wheel?