DEV Community

Cover image for I rebuilt my portfolio🌻 Now it loads in 1.6s 🎉 Here's how I did
Saurabh Daware 🌻
Saurabh Daware 🌻

Posted on

I rebuilt my portfolio🌻 Now it loads in 1.6s 🎉 Here's how I did

Note: This article is only intended to explain how I am loading my site. These steps may change as per your use case (Building an E-Commerce website with Vanilla JavaScript is not a great idea)

Hi, everyone!

So my old portfolio used to load in 4.2 seconds and had a performance score of 43 so I decided to rebuild (and redesign) my portfolio site and now it loads in 1.6 seconds and has 100 lighthouse score! (the link to the website is at the end of this article)

It is built using Vanilla JavaScript and does not use any external script or stylesheet (except the one for google font).

Here are performance insights from lighthouse

Google Lighthouse score of saurabhdaware.in

TLDR

So for better performance, I am :

  • Using rel="preload"
    <link rel="preload" href="assets/css/index.css" as="style" media="all" onload="this.onload=null;this.rel='stylesheet'">
  • Split CSS into index.css & mobile.css and loading mobile.css in mobiles only
    <link rel="stylesheet" href="assets/css/mobile.css" as="style" media="screen and (max-width:768px)">
  • Lazy loading images
  • Using CDN (I'm using Cloudinary It also provides me a way to change the width of the image in request time so I load the image of the same size of the one to be rendered.)
  • Using OffScreen Canvas (to be honest don't use it, its experimental and only works in chrome. I managed to do some workarounds that ignore the offscreen canvas and load the same file as a normal script in unsupported browsers)

Here's how I improved the performance


Table of Content


Preloading Resources

When you hit a link in your browser, the browser starts parsing index.html file but by default browsers halt the parsing when they come across <script>, <link>, <style> tags as they can alter the paint of the document. Thus blocking the initial paint.

By preloading the resources you can load the file without blocking the first paint. So the loading of these files starts as usual but the paint is created before the CSS or scripts are loaded.

Super cool right? well, with great power comes great responsibility!
You don't want your website to look like this on the first load no?


First load when CSS has preload


Since we are painting screen without loading CSS, This is how the website will appear for first few milliseconds.

How to handle this?
This is how I do:

When the user loads my website all I want to show is a blue screen then load the content when CSS is loaded

index.html

<head>
    <!-- Other head tags -->
    <link rel="preload" href="assets/css/index.css" as="style" media="all" onload="this.onload=null;this.rel='stylesheet'">
    <style>
        html,body{
            background-color: blue;
        }
        .lazyload, .main-container{
            display:none;
        }
    </style>
</head>
<body>
    <header>
        <!--Header content -->

        <h1 class="lazyload">Hi, I am Saurabh welcome to my website!</h1>
    </header>
    <main class="main-container">
        <!-- Main Content -->
    </main>
    <!-- Remaining HTML -->
</body>

This keeps the main-content and some text from header hidden

Then in index.css I do.

.lazyload, .main-container{
    display: block !important;
}

which overwrites the rules in <style> and displays the content

I am not exactly using the same code as I explained above. I do some animations to make the text appear so the output looks kind of different than what it would look with the code above

How my website loads slides

Splitting CSS

If your media query for the mobile is too large, it makes sense to have a separate file for it since the code is completely useless to load on desktops.

<link> tag provides us option to load css file only in the device that matches the media attribute value

<link rel="stylesheet" href="assets/css/index.css" as="style" media="all">
<link rel="stylesheet" href="assets/css/mobile.css" as="style" media="screen and (max-width:768px)">

With this mobile.css file will only load in the device that matches screen and (max-width:768px)

Image Optimization

Lazy loading

Fun fact: Browsers will soon have loading="lazy" attribute in IMG tag. Till then this is what I'm doing:

<img id="projectimage-1" src="placeholder.webp">
<img class="lazyimage" data-cover="projectimage-1" style="display:none;" src="actualimage.webp">

<script>
function loadProjectImage(e){
    const image = e.target;
    document.getElementById(image.dataset.cover).src = image.src;
}
document.querySelectorAll('.lazyimage')
    .forEach(imgEl => imgEl.addEventListener('load', loadProjectImage))

</script>                        

Using CDN

CDN or Content Delivery Network respond faster with the image than your usual server.

Apart from this advantage, there are some customizations that Cloudinary (CDN that I use) provide that helped me in faster optimizations.

Having .webp extension is good for websites since it provides better image optimizations, with cloudinary you can simply change .png or .jpg in image URL with .webp and it generates webp image for you!

Also, cloudinary provides a way to resize images by passing parameters in the URL

This is how a cloudinary image URL looks like:
https://res.cloudinary.com/saurabhdaware/image/upload/c_scale,w_300/v1552455020/saurabhdaware.in/projects/eotm-portfolio.webp

In this, w_300 represents the image with width 300. Changing the value will give you an image with that width. So you can dynamically change this value in JavaScript to load the image exactly of the same size of your render.

And Hey, Cloudinary! if you're reading this, please pay me :3

Bonus

Also, apart from these factors, I've used OffScreenCanvas to render header animations in the web worker but since it is an experimental feature I don't really think so it is the right time yet to have it in your production.

And I won't say that not using libraries made it fast. But yes, Not using framework allowed me to have better control over files so I could decide which files to preload and when to load which file and how to bundle them together.

However, You can use libraries and still load the website fast. You just need to handle it properly but yes in case of small websites like portfolio, it does make sense to avoid having these huge libraries which are larger than your whole website itself.

And DONE 🎉💃


I hope you liked the article!

My Portfolio Link: https://saurabhdaware.in
(Hovering or tapping on some elements in the website may create surprising results 😉)

I would love to receive some feedback on my portfolio site🌻

Oh, and I also redesigned my website logo

saurabhdaware.in Logo

Thank You!

Latest comments (84)

Collapse
 
abhisheksankpa6 profile image
Abhishek Sankpal

Hi write blog on razorpay interview ...

Collapse
 
abhilearnstocode profile image
Abhii

Great article buddy!!
And...
That discussion between @technomad and @clodder is worth a read!!!

Collapse
 
unsungnovelty profile image
Nikhil

Ever since I have seen this post, I have been working on improving my website and I am 100 all the way now. Thanks for the inspiration man!

webdev
unsungnovelty.org.

PS: Yes, I like my website plain and minimal. :)

Collapse
 
saurabhdaware profile image
Saurabh Daware 🌻

Thank you so much :D

Collapse
 
olesbolotniuk profile image
oles-bolotniuk

Cool looking website doe

Collapse
 
stephenmirving profile image
Stephen Irving

You can preload image and javascript assets as well. Another suggestion for optimizing is to create image sprites for small images like icon sets or logos or other images that are small and similar or limited in color palette. Lots of npm packages that can help you with that, but easiest for people just starting to make them is one of the online generators like toptal.com/developers/css/sprite-g...

or spritegen.website-performance.org/

Another good optimization regarding images is to make sure the images are not only sized correctly, lazy loaded and/or spritified, but also that the individual images have been fully optimized. Again, lots of npm packages for that, but easiest for beginners is to use a GUI application like FileOptimizer, which I think is very good. Can download that here: sourceforge.net/projects/nikkhokkh...

Collapse
 
saurabhdaware profile image
Saurabh Daware 🌻

Oh, these are some really helpful tips! Thank you so much I will check them out :D

Collapse
 
stephenmirving profile image
Stephen Irving

The lack of spaces before the opening bracket of a code-block makes me want to throw up.

Collapse
 
saurabhdaware profile image
Saurabh Daware 🌻

Hi, can you tell me which code-block are you talking about? I will fix it.

Collapse
 
stephenmirving profile image
Stephen Irving • Edited

I'm just giving you a hard time - I liked the article.

This is what I'm talking about though, no spaces before the opening bracket:

function loadProjectImage(e){

You do it in pretty much every code block in the JS and CSS:

html,body{

.lazyload, .main-container{

Like I said though, just giving you a hard time. It is a style thing and I'm pretty anal about style. it was a good article. Thanks.

Thread Thread
 
saurabhdaware profile image
Saurabh Daware 🌻

Oh I see. I think it totally depends on how you (and your team) prefer it.
I've seen a lot of w3 articles not putting any space there. Even a lot of code snippets in this article about JavaScript best practices - w3.org/wiki/JavaScript_best_practices do not add any space in the code.

So yeah it depends on how you are linting that particular project :)

Thread Thread
 
saurabhdaware profile image
Saurabh Daware 🌻

Just checked google.github.io/styleguide/jsguid... and yes they mentioned about the space before brackets :D

Thread Thread
 
stephenmirving profile image
Stephen Irving

Too funny! I was just about to link the Google style guide for you. Ya, Douglas Crockford recommends it as well: crockford.com/code.html
As well as every other style guide I've seen. Interesting that the w3 best practices doc writes them that way, I hadn't seen that.

On another note, I've also seen it said that it is against best practices to pass the event object around. Here is a link to the page of the book I saw it in, Maintainable JavaScript, thought you may be interested (it is a very good book too, I always recommend it, as well as JavaScript Patterns by Stoyan and JavaScript The Good Parts by Crockford:

books.google.com/books?id=bHhlCrvb...

Collapse
 
harrytheo profile image
Harry Theo

Those are some pretty awesome optimisations! well done!
Love the animations 😊 If you would like to restart your austronaut animations check out my article 😉
link.medium.com/1CKzyKfNU1

Collapse
 
saurabhdaware profile image
Saurabh Daware 🌻

Thank you for your kind words🦄 reached the end of my medium limit :) I will read it later thank you for sharing :D

Collapse
 
lcjury profile image
luis jury senn

You should try to put your css inline in your html. May not be the best practice, but your css it's really small, maybe, killing one (or two) requests worth it :)

Collapse
 
saurabhdaware profile image
Saurabh Daware 🌻

That will surely help me in 'getting the content along with the styles and overall colors' as soon as possible but my index.css is still large and making it inline will just block the first load for some time.

Since they are preloaded they don't really make any change in the first load right now so I can afford having that extra request :D

Collapse
 
technomad profile image
Tech Nomad

What about 300ms for a WordPress + Vue.js site? ;)
wue-theme.app

(Server in Frankfurt without CDN, so in USA it could take around 2 seconds to load).

Collapse
 
xcs profile image
XCS • Edited

This looks cool, congrats for the work!

So can I use any WordPress plugin and it will work with the theme as with any other theme? If yes, that's amazing, if not, what is the purpose of using WordPress at all, as I know WordPress is all about the ecosystem (themes/plugins)?

Collapse
 
technomad profile image
Tech Nomad

Hey, thanx for the star on Github :D
"So can I use any WordPress plugin and it will work with the theme?"
Yes, the theme works POTENTIALLY with any plugin. But it only provides the basic concept. You have to build everything you need on your own. But Yoast SEO for example works out of the box. Also any plugin which relies on wp_head() and wp_footer().

The problem with single page apps was primarily the SEO. And that problem does the theme solve without server side rendering (Nuxt.js) which brings some disadvantages (separated node.js server; you can't use the window object).

So you will still have to implement all the features like comments, forms etc yourself. And it's really hard work. I'm working for almost half a year full time on a commercial version of this theme which will include or does already include Polylang / WPML, Elementor, WooCommerce, Categories, advanced ajax comments, Subcategories, advanced Ajax Search, Vue Form Builder, Advanced Vue Mailchimp Plugin, Theme-Options powered by Vue.js as well. But it's still far from being released. I'll hopefully will publish next week a first MVP version, which is already really, really cool, but I will offer it only together with individual customisation starting at 1500€. But next year I hope to make it available as downloads at lower prices.

Collapse
 
clodder profile image
Lodder

Your time to interactive is 3.3s on slow speed network. Test your site on web.dev

Collapse
 
technomad profile image
Tech Nomad

Just checked web.dev as well. All Measures are between 85 and 97 points. So what's the point?
thepracticaldev.s3.amazonaws.com/i...

Thread Thread
 
clodder profile image
Lodder

Do you know what each of the scores (in seconds) actually mean?
Fair enough if you're happy with 3.4s on TTI :)

Thread Thread
 
technomad profile image
Tech Nomad • Edited

No, I don't know what each score on web.dev - a site I heard first time 2 minutes ago - means.
And yes, I'm very proud and happy about 300ms page load of a Wordpress + Vue.js + GSAP site and which is actually even faster than your site (joomjunk.co.uk up to 450ms) build with pure html and with 10 lines of JavaScript and CSS. You obviously taking this parody here too seriously:
motherfuckingwebsite.com

It's not my problem if you browse the internet on a feature phone ;)

Thread Thread
 
clodder profile image
Lodder

Well according to Pingdom, you're coming back at 480, not 300,but either way...

75% of the website is viewed on a mobile, so it's mobile that's important to target in regards to performance....and yes, that includes 3G connections.

Not taking that parody seriously at all.

You have have a faster response rate, but on 3G, your site will take 4x longer before the user can interact with it. Just an FYI :)

Thread Thread
 
technomad profile image
Tech Nomad • Edited

You have a very fast site and you can be proud of it. But I just don't get why you want me or other users here make believe my fully functional, cutting edge WORDPRESS (which is famous for being slow) site for realistic usage with an elite Lighthouse mark of 94 points would be slow. That's just insane. Actually it's defamation.

You wrote something about 3.3 seconds to first interaction with my site - this would mean a connection of 200kb/s - seriously? Is this your target group? ~1% of devices in the western hemisphere or some people hiking through woods, tundra or desert? I bet you make a lot of money with such of sites... Also even web.dev says 3.3 seconds (for prehistoric phones / bad connection) is very good (green).

Did you know 3G is going to be shutdown within next 2-4 years? In India, USA and Europe many providers will shut it down next year. You better should catch up with modern web technology ;)

I also don't know where you get your numbers from. 75% wtf? The figures I read all the time are around 50%. And how many of them are still using 3G?

"Well according to Pingdom, you're coming back at 480, not 300,but either way..."
I build websites for people not for bots. Pingdom can't render Single Page Applications. Did you hear about this technology? It's the new kid on the block... since 2002/2003 ;) So Pingdom is rendering my Search Engine Non JS Bot Markup which is not performance optimised at all.

So on my DSL Desktop your site is 100-200ms slower than mine. But you can be proud of you. People in the woods can "interact" with you site after 0.8 second!

Stop trolling man.

Thread Thread
 
clodder profile image
Lodder

95% of the UK will be covered by 4G. You then have to remember those who commute to work where there is a poor connection in many areas, or even public networks such as cafes. There are still thousands of areas in hundreds of countries that dont yet have 4G coverage.

Why do you think the leading audits tools (based on lighthouse) give you a throttled result? Because it's important. It's reality.

If you do some research on companies that have seen huge bounce rate improvements due to shaving a single second off their TTI, you'd be surprised of the outcome.

I'm not trolling at all. Ask anyone who knows their shit about site optimosation

Thread Thread
 
technomad profile image
Tech Nomad

You should stop to generalise and judge about others on your personal preferences. If your main target group are people with feature phones, poor connections (for what ever reasons) - it's totally fine, it's your business. But when you say my site is slow because it takes 3.3 seconds to load from the woods - then you are just rude. According to all performance optimisation tools my site is still very good even when throttled. It's not as good as yours in the woods, but it's still good, so don't tell me my site slow. It's fooking elite.
"Ask anyone who knows their shit about site optimosation"
You're talking here to such a one.

Thread Thread
 
clodder profile image
Lodder

~ cutting edge WORDPRESS.

Hahaha oh please...

~ You should stop to generalise and judge about others on your personal preferences.

Nothing to do with personal preference. A large % of the web is viewed on mobile. It's nothing to do with "being in the woods".

TTI is also a very important UX factor.

The truth hurts, so take it as being rude or not, but my point still stands, whether you like it, or not.

Thread Thread
 
technomad profile image
Tech Nomad • Edited

"Hahaha oh please..."
Please what? There are not many Single Page App's based on WordPress out there. You don't think Single Page Apps are cutting edge?

"Nothing to do with personal preference. A large % of the web is viewed on mobile. It's nothing to do with "being in the woods".

You started this dumb discussion not about mobile web. But about prehistoric 3G connections. How many % of the mobile traffic is made with a 200kb/s connection? And yes 200kb/s you get only in the deepest countryside in the western Hemisphere. Even the third world is pushing 4G/5G as its cheaper than physical wires.

"TTI is also a very important UX factor."
And the "TTI" of my site is very good. So what's your fucking point?

"The truth hurts, so take it as being rude or not, but my point still stands, whether you like it, or not."
Yeah, please tell me what's your point?

Is all you wanted to say is that my site isn't as fast as yours in the woods? Great!!! Did you apply for an Awwwards nomination?

Thread Thread
 
technomad profile image
Tech Nomad • Edited

"TTI is also a very important UX factor."
Show me some examples of your great UX work where you respect not only the factor of being able to load a site from the woods within 0.8s (people on the countryside and in the woods are very busy and have no time to loose) but respecting circumstances and factors relevant to the other 99% of the users. Or is your beautiful site the only one you've build so far?

Seriously I can't imagine any sane client would let you build a business site based on your "UX" skills (except the 0.8s page load from the woods) you show here: joomjunk.co.uk.

Thread Thread
 
technomad profile image
Tech Nomad

I don't fully understand why you've tried to diss my site, but doing so you only embarrass yourself.

Thread Thread
 
technomad profile image
Tech Nomad • Edited

By the way 3G means a speed of up to 15Mbits/s which is ~2MB/s.
Even my first smartphone ever - iPhone 4 - which I bought in 2010 or 2011 had a speed of up to 1MB/s (or ~8Mbit/s).
appleinsider.com/articles/10/06/25...

So this dumb and embarrassing discussion is not even about 3G but really prehistoric devices and countryside with a very, very bad infrastructure (woods and fields!).

So please stop embarrassing yourself and waisting my time. I will not response to your bullshit anymore.

Thread Thread
 
clodder profile image
Lodder

Did I hit a nerve?

Collapse
 
technomad profile image
Tech Nomad
Collapse
 
technomad profile image
Tech Nomad

ehm, I don't know what web.dev does and how. But Google pagespeed insights says my site is quite ok ;)

Collapse
 
saurabhdaware profile image
Saurabh Daware 🌻

That is really cool! Would you mind sharing what you're doing for the first load?

Collapse
 
technomad profile image
Tech Nomad

Thanx :)
First of all a VPS server with a handmade nginx, MySQL and PHP setup. Then also the theme itself is fully handmade without any plugins that could effect the speed negatively (e.g. WPML). Only those measures already drop the loading time to ~600ms. Then WP Rocket does the rest :)

Thread Thread
 
saurabhdaware profile image
Saurabh Daware 🌻

woaahh so cool 🦄🦄 I have no idea about server setup and deployments tbh mine is hosted over netlify 😂🕺 Thank you for sharing it was super informative🌻

Thread Thread
 
technomad profile image
Tech Nomad

On udemy there is a bunch of nice tutorials. I didn't watch this one, but it has great ratings:
udemy.com/course/wordpress-the-def...

Collapse
 
lauriy profile image
Lauri Elias

Isn't that kind of slow though? : )

Collapse
 
saurabhdaware profile image
Saurabh Daware 🌻

It is! I am still trying to improve it, its just that I'm proud of whatever I did till now.

Also, I don't think so there will be any major changes in the load time now. The thing is, After this point if I want to improve the performance I would have to compromise on the content (by deleting elements) or compromise on accessibility or seo (by rendering in javascript).

Eventually its not about providing the fastest website rather providing them with a good overall website which is comfortable to maintain, doest not take tooo long to load, and has good accessibility and seo. :)

Collapse
 
dhanushp profile image
Dhanush Bangera

If you want fast static site, Gatsbyjs FTW ❤️

Collapse
 
piotroxp profile image
Piotr Słupski • Edited

Saurabh, your rocket game is unbeatable.

Collapse
 
saurabhdaware profile image
Saurabh Daware 🌻

Thank you so muchh! It's a old project though so there are some mistakes. for the next few months I'll be working on games only so probably will end up building better games :D Thank you 🌻

Collapse
 
clodder profile image
Lodder

1.6s is still pretty poor for a static site.

Collapse
 
saurabhdaware profile image
Saurabh Daware 🌻 • Edited

Yeah I'm still working on improving it :D
I'm just very proud about it since it has canvas animations a lot of colors, images etc. 🦄

Collapse
 
clodder profile image
Lodder

I personally use Javascript to load all JS/CSS files asynchronously. With the Joomla CMS powering my site and on SiteGround hosting (pretty bad TTFB times), I can manage 0.8s for first interactive

Thread Thread
 
saurabhdaware profile image
Saurabh Daware 🌻

I am loading them asynchronously too. In fact I'm preloading them and applying them when they are loaded that should be faster than straight up loading them. Is there anything extra you're doing? Would you like to share your website?

Thread Thread
 
clodder profile image
Lodder • Edited

This is what I wrote to properly asynchronously load JS gist.github.com/C-Lodder/a00cf9894...

You can use it for CSS too. My main template CSS I'm loading inline as I wrote my own mini framework and it's only 22kb

Alt text of image

Thread Thread
 
saurabhdaware profile image
Saurabh Daware 🌻

that looks interesting I have async attribute true in my script link, I'll do some research. Thanks for sharing! the performance insights are pretty crazy :D

Collapse
 
dengson12 profile image
Dengson12

Really cool portfolio site

Collapse
 
saurabhdaware profile image
Saurabh Daware 🌻

Thank you :D