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.
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:
- Can this be done in HTML?
- If not, can I solve it with HTML + CSS?
- 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;
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>
The CSS:
.fade-in {
opacity: 0;
animation: fadeIn 2s;
animation-delay: 2s;
animation-fill-mode: forwards;
}
@keyframes fadeIn {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
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.
Top comments (120)
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!!!!!!!!!
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
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!
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.
Hi, interested in your book
I sent you the link in Chat. Thanks
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
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
\o/ ça serait avec joie
I did exactly this, now I'm going back and learning the basics properly! I'd love a link to the book! Thank you :)
I've followed you. Please just follow me here at dev.to so I can Chat (DM) and send you the link. thanks
Can I please get a copy
Happy to send you the link, but please follow me here on Dev.to so I can send you the link in Chat. Thanks
Yes just did
Please send a copy
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
I sent you the link in Chat.
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!
I sent you a copy in Chat. 😊
Would love to have your book thanks!
Thanks, I sent you the link in Chat.
Interested in your book. Just followed you also. May I have a free copy please
I sent you the link in chat.
Hi Raddevus,
I am a newbie webdev, I'm interested in book.
Thanks.
I sent you the link in Chat. 😊
I sent you the book in chat.
I sent you the book in Chat.
Hello pls I need a copy of your book
I sent you the link in Chat. Thanks
Hi, I'm interested in your book. May I please have a copy? 🤗
Please follow me here on dev.to and I will Chat you and send you the link to the free book. thanks
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 :)
I sent the link to you in Chat. 😊
I would like a copy, as well, please. Thank you
Please follow me here on Dev.to so I can Chat you and send you a link to my book. thanks
I sent you a copy in Chat.
Hey, I am interested in your book as well! Thanks in advance!
Please follow me here on dev.to and I'll send you a link to the PDF book in Chat. Thanks
Thanks so much for offering the book, would love to get a copy amackp@gmail.com cheers!!
Please follow me so I can Chat you and send you the link to my book. thanks
I just started learning html and CAD. I would love a copy of the book
I meant CSS.
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
Hey can I get the book please. I've followed you
I sent you a copy in Chat.
heard you're giving away a book ..
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.
Hello, I am interested in your book and would love to get a link as well, thank you.
I sent the link in Chat.
Would love a link to your book and thanks in advance!
Hi! I am new here but I feel the needs of more understanding of front end recently. I am really interested in your book.
Hi, I would love a copy of your book, thanks!
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
Following!
I sent you the book in Chat.
Very intrested!
Please follow me here on Dev.to so I can Chat you and send you the link to the free book. thanks
Hi, I would very much appreciate a copy :)
Please follow me here on Dev.to and I can send book link via Chat. thx
I sent it to you in Chat. Thanks
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
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.
If you will please follow me here on dev.to I will send link via chat
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.
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.
It's because we assume that it's such a basic that you can't do react without html and a minimum of css
Absolument d'accord, maîtriser du html et du CSS la base.
Very important comment. It's a kind of plague nowadays.
Blasphemy!! Get 'em!!!
I totally agree! And sadly know what you're talking about 🤷♂️
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.
Thanks ☺️
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?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?
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
andrelative
positions.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.
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?
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.
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.
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.
So I tried it, and JS is alot easer to debug than css.
Easier how? I am not certain how that example should be read or executed to validate your point?
I see what you did there!
Working with SPAs, PWAs and hybrid apps I cannot escape using JS/TS, but you have valid point there. For a static site there are several approaches but the one I like the most is the idea and concept behind 11ty as its output is as 'pure' as it can be.
Never do things with JS if you can do it with CSS - that's both sane decision as well as using technologies the way they are intended to be used.
Also, I would add -> use HTML tags as they should be used,
div
is okay, but too many apps and pages are suffering fromdiv-itis
.Yeah, totally agree, but can't fit everything in one post. I could write another post about the importance of semantic HTML.
Meanwhile you can read this amazing post by my colleague Eevis: dev.to/eevajonnapanula/ode-to-sema...
PWA can be a regular HTML + CSS + req/res looped website with just the service worker thing installing the PWA, no need to go "all in" with JS/TS there either.
I totally agree that you should strip everything you don't need and that mostly depends from project to project. PWAs I was working on were mostly data driven apps and were interactive. Can't have real time graph without at least some JS on client considering there was no SSR mechanism included.
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.
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.
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.
I think this is also a problem that is not React specific. This problem will occur in every project that grows large enough.
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.
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.
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.
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.
Thanks for the comment! Perhaps you could write a blog post about your experience?
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).
"This way of thinking is not about what is easiest for you as a developer" - ok, but this is what makes it a losing way.
All other things being equal with respect to the outcome given business requirements, things should go with what's easiest for a developer.
Easiest for a developer (as long as architecture is respected) translates into quicker time to market and lower development costs. Long term costs should be addressed by architecture and other business constraints (such as hiring market, other costs, etc).
Unless there's a significant impact to the end result for that business requirement, I see no reason to go against a developers toolset.
But you should always consider the cost from the end-user point-of-view. Think about accessibility or browser support for example. It's not fun or easy for you as a developer, but it makes it possible for your (possibly paying) users to use your service!
I disagree. You don't. That's a business decision that depends on how the product was defined to target and support. What you (eg: developer / architect) should do is present the options and constraints to business to make a decision.
Doing in this way means a certain time-to-market and development costs but it may leave out or otherwise impact users.
Doing it the other way may come with extra costs in terms of development but may results in other advantages.
Middle way: we could start one way but there may be extra overhead to design it in a way that allows a reasonable time to change later on.
Then the business decides. It's perfectly reasonable to knowingly limit browser support for example if it's cost effective to market earlier. It's not a development decision.