10 Tougher Tasks to Reduce Page Weight

Contributing Editor
This entry is part 2 of 4 in the series Reducing Page Weight

Reducing Page Weight

In my previous article, 10 Quick and Easy Fixes to Reduce Page Weight, I discussed basic techniques that slim your site without fundamentally changing code. If your pages are still obese, there are more drastic dieting options you can contemplate…

1. Remove social network buttons

Do you have Facebook, Twitter, Google+ and LinkedIn sharing buttons on your pages? That’s 580Kb of content you’re serving to frustrated end users. Much of it is JavaScript that must be executed by the browser and some networks stipulate it must be loaded before your content appears.

Bloated social widgets are completely unnecessary — you can add fat-free social buttons to your pages with a few lines of HTML. A little JavaScript can progressively enhance the experience and show a pop-up window on desktop devices.

While simple buttons won’t show click statistics, you can discover far more information with event tracking in Google Analytics.

2. Check all third-party widgets

Social networks aren’t the only culprits. Adding third-party widgets to your page has a hidden cost that significantly exceeds the included markup. Even if the content is loaded from another domain, it may contain hundreds of kilobytes of data, JavaScript, CSS, and images.

If you must use a widget, consider one that is better written. Ideally, the widget JavaScript should be lightweight, loaded at the end of the page but able to place content in a specified HTML container. Alternatively…

3. Consider lazyloading — or on-demand content

Presume you’re showing a video hosted by a specialist provider. While the video is downloaded only when the user hits “play”, you are probably loading video API code and other related resources regardless of whether the user plays the video or not. Why not load all that content when the user requests it?

You can also consider on-demand images and content that download as the user scrolls the page. I’m not a fan of the technique; it can potentially have a negative impact on usability or SEO. However, it is useful for some types of web applications–for example image galleries.

4. Replace images with CSS3 effects

Are you slicing images to create gradients, rounded borders and shadows? I hope not — CSS3 makes such techniques redundant.

The effects won’t work in IE8 and below but oldIEs are dying and users won’t be aware because they won’t compare your site in multiple browsers. You can add clever shims such as CSS3 PIE but I wouldn’t recommend it: they can bulk up your page and make the older browsers slow to a crawl.

CSS3 effects generally degrade gracefully so it’s rare you need worry about older browsers. Pixel perfection has always been futile and is utterly ridiculous when you’re building responsive designs that adapt to different screen sizes.

A note of caution though: CSS shadows and gradients have been shown to be costly during browser repaints, especially if you’re displaying dozens of elements with these features added. So use the effects sparingly and test scrolling performance and repaints before committing to overusing these effects to replace images.

5. Replace JavaScript with CSS3 effects and animations

Is your JavaScript littered with $("#x").fade() and $("#y").slideDown() effects? That may have been necessary a few years ago but CSS3 animations, transitions and transformations have to a large degree superseded JavaScript effects. The reasons:

  1. CSS3 animation is natively handled by the browser; if it’s done right, it will often be much faster and smoother than JavaScript execution.
  2. CSS3 animation is easier to write and requires significantly less code.
  3. CSS3 offers 3D transformations which are extremely difficult — if not impossible — in JavaScript alone without a specialized library.

There are situations when you want fine-grained JavaScript control but they are rare exceptions. Again, effects won’t work in old browsers but should degrade gracefully.

6. Consider Scalable Vector Graphics (SVGs)

SVGs contain points, lines, and shapes defined as vectors in XML. SVGs are ideal for responsive designs since they will scale to any size without loss of quality and the file size is often smaller than a bitmap.

SVGs aren’t suitable in all situations. Photographs and complex images will always be better as a JPG or PNG. However, logos, diagrams, and charts are usually appropriate. What’s more, SVGs can be manipulated on the client using CSS and JavaScript.

There are tools that convert bitmaps to vector format, but starting from scratch will yield the best results. Packages such as Illustrator, Inkscape, and SVG edit provide a good start, although learning XML basics will help you produce cleaner code.

7. Replace images with icon fonts

You may have dozens of small icons in use throughout your site and managing individual image files isn’t fun. Fortunately, icon fonts can save space and sanity. A single font can contain hundreds of vector-based images which can be set to any color and scaled to any size in all browsers (going back to IE6).

You can use a dedicated font or, for optimal bandwidth-saving, use a tool such as Fontello, IcoMoon or Flaticon to create a font pack containing the icons you need.

8. Use image sprites

Bitmap images should be the last choice once CSS3, SVG and icon font options have been rejected. Often-used bitmaps can be packaged into a single sprite file so individual images can be accessed in CSS, e.g.

.sprite {
	width: 16px;
	height: 16px;
	background: url("sprite.png") 0 0 no-repeat;
}

.sprite.help { background-position: 0 -16px; }
.sprite.info { background-position: 0 -32px; }
.sprite.user { background-position: 0 -48px; }

The advantages:

  1. You require a single HTTP request to load the sprite.
  2. A single sprite will normally result in a smaller overall file size than the total weight of the individual images.
  3. All images appear when the sprite has loaded.

Image sprites can be created in a graphics package or using tools such as Sprite-Cow and Instant Sprite. You can alternatively incorporate sprite production in your Grunt workflow.

9. Use data URIs

Data URIs encode binary and text assets as if they were external resources. Bitmap images and SVGs can be encoded directly in HTML, JavaScript, or — more usefully — CSS:

.bullet {
	background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQAQMAAAAlPW0iAAAABlBMVEUAAAD///+l2Z/dAAAAM0lEQVR4nGP4/5/h/1+G/58ZDrAz3D/McH8yw83NDDeNGe4Ug9C9zwz3gVLMDA/A6P9/AFGGFyjOXZtQAAAAAElFTkSuQmCC");
}

This will reduce the number of HTTP requests — although maintenance is more difficult unless you can automate the process in some way. I would only recommend it for small, often-used images that are unlikely to change.

Tools such as DataURL.net and data: URI Generator will convert files to data URIs for you.

10. Use website assessment tools

You won’t know whether your diet has been successful unless you’re monitoring your page weight and the resulting download speed improvements. Browser developer consoles and free online tools such as Google Page Speed Insights can help. A comprehensive list is coming in my next article before we discuss more radical, liposuction-like page weight reduction techniques in the last part of this series.

Reducing Page Weight

<< 10 Quick and Easy Fixes to Reduce Page Weight10 of the Best Web Page Weight Analysis Tools >>

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • http://love2dev.com/ Chris Love

    Great list Craig, keep up the good work!

    • Craig Buckler

      Thanks Chris – appreciate it!

  • sdbritton

    As always, great work Craig!

    I also want to add one more suggestion – if you are using a library, like Bootstrap, Foundation, Gumby, etc. – remove unnecessary and unused elements, like buttons and other assorted eye candy that is not being used on the site.

    New Year’s resolution – do away with code bloat!

    • Craig Buckler

      That will be mentioned in the last article in this series…

      • http://surrey-webdesign.net/ ThreeQuarter

        Or dont use a framework, code it yourself Too many obvious bootstrap sites out there now, just do it yourself and you will have full control

        • http://www.isights.org/ Michael Long

          That presumes that you can do a better job than the framework authors… which is doubtful. They’re pretty smart guys, and it likely that any given framework will have been pounded on by thousands of people, thoroughly debugged, and tested on browsers that you’ve never even heard of.

          Further, and perhaps more importantly, why burn your time reinventing the wheel? Spend it implementing features on your site.

          And it a site is “obvious” bootstrap, then just download the source and the LESS files and skin the silly thing to your liking. Again, it’s faster than doing it all from scratch.

          Of course, you’d have to spend a little bit of time learning to use Bootstrap, and that’s probably the real reason we have so many “full control” freaks out there. Too lazy to crack open the documentation and spend a day playing with the code.

          Nope, they’d rather spend six weeks implementing their own version…

          • Craig Buckler

            Hmm. Not sure I totally agree. Frameworks are generic rather than built for purpose. It doesn’t matter how good the authors are – they weren’t necessarily trying to solve the problems you are. It may be faster that starting from scratch but authors who do will learn considerably more and become better CSS developers. It will also make them better at using Bootstrap because they’ll understand the root causes of any problems.

            Besides that, it’s always possible you’ll invent a better wheel!

          • http://www.isights.org/ Michael Long

            As I said, the popular ones, like Twitter Bootstrap, or jQuery Mobile, have been selected and gone through a pretty rigorous debugging process by thousands of people on hundreds of platforms. As opposed to my purpose-built solution which probably works on the half-dozen browsers I spent a half-hour testing them on.

            That’s why I said I doubt a scratch solution will be better. Now, if you have some fairly specific or extreme requirements, then we can talk, but until then I’d go with the framework first. Why?

            Well, debugged was point one, but point two is that there’s a good chance the framework does do what you want. You just haven’t dug deep enough to find out.

            Third, unlike your own solution, the framework is thoroughly documented. There may even be sites and books and training courses devoted to it.

            Fourth, and related to three, using a framework means that there’s probably a team of developers out there that already know it, understand it, and can take over and maintain your project from day one, should the need arise. Not to mention an entire support community that’s available to ask questions.

            Fifth, using a framework or two or three for various projects gives you a mental “framework”, or basis for doing your own. After all, even if you have specific needs, or if a framework may be overkill, your own solution will still probably have to handle all of the non-specific use cases and styling and fonts and sizing and responsiveness and so on that a more “generic” solution handled for you.

            Sixth, requirements change. Yeah, TB or jQM looked like overkill and so you rolled your own. But now you’ve shown the result to the client and he wants it different. Or he’s excited, and now he wants to add feature A and B and C and D, all things your purpose-built solution doesn’t support and which you’ll now need to cobble together.

            Seventh, is related to overkill. Yeah, if all you need to do is style a single page, or swap a few classes in the DOM, then TB or jQuery is probably overkill. If, however, you’re doing a major web site or project, and you aim to replace TB or jQM or Bootstrap or Angular with your own solution… then we need to talk.

            So that’s my case. Yes, it’s possible you can do a better job, and it’s possible you have specific requirements that using a framework precludes, and it’s possible for you to take six weeks (or months) out of your development schedule to roll your own, and it’s possible your solution covers all the bases and will be thoroughly documented and tested and supported…

            Yep, it’s possible to invent a better wheel. But I submit that any given developer thinking of “rolling their own solution” consider all of the above first.

          • Craig Buckler

            I guess you really like frameworks?!

            My only points:
            1. Frameworks also contain stuff you don’t need.
            2. Frameworks rise, evolve and disappear.
            3. Overriding or fixing framework code can take longer than writing it correctly.
            4. Using a framework without understanding how it works can lead some to become cut-and-paste coders. That’s not interesting or well-paid work.

            I’d never say don’t use a framework, but don’t presume they’re right for every project.

          • mickyhulse

            Related to your #2 point: Using plugins and frameworks can also be a crutch in terms of updates and upgrades. There’s possibly more long-term maintenance when you commit to using these types of things (especially if you use a lot of them).

            I currently have a job where I have to maintain the stuff I implement. This is probably the main reason why I like to build my own plugins/”frameworks” (following best practices of course). I think there’s a lot of “developers” out there who implement sites/products and don’t have to maintain them for the long term. It’s probably easy to build a site for a client, use a ton of plug/frameworks, get a paycheck and move on to the next client. There’s definitely nothing wrong with that, and there are times I wish I could do that myself … but I do believe that one can learn things about development work, that they’d never learn otherwise, if they have to maintain their own messes (for the long term).

            Like you say, there’s a time and a place for everything. I’m not opposed to using a framework/plugin. I think it’s important to keep an open mind. I’m just glad I know enough to build things from scratch when the job requires it.

          • http://www.isights.org/ Michael Long

            A couple of points here:

            First, I think one needs to be careful in picking their tools. There’s a big difference in using a major framework like jQuery Mobile or Bootstrap, as opposed to grabbing what appears to be the closest match off the WordPress plugin rack. The big boys have community and support, and are likely to be maintained even if the lead developer quits or loses interest.

            Which leads to support for custom “home brew” solutions. Not to put too fine a point on it, but if you quit or leave, who’s going to be able to come in and pickup where you left off?

            I just came off an article about how PayPal is moving off its own custom built Java frameworks that require a 6-week orientation course, and moving to public, open-source frameworks running on node.js. Not only is development faster, but new hires familiar with Bootstrap or Kraken or Dust can hit the ground running.

            Finally, I definitely agree that one should know how to do the job, even without a framework.

          • http://surrey-webdesign.net/ ThreeQuarter

            so if I write my own framework (yep, doing it!) you would believe my work superior because it comes from a framework?

            Also you keep mentioning JQ Mobile, Im not sure that qualifies as a ‘framework’ per se in the same way as Foundation or bootstrap do in terms of this discussion.

          • http://www.isights.org/ Michael Long

            There are JS frameworks (jQuery, Prototype), CSS frameworks (Bootstrap, Semantic UI), MVC frameworks (Angular), UI frameworks (jQuery UI), mobile frameworks (jQuery Mobile, Sencha), and more.

            And no, a framework isn’t superior just because it’s a framework. But like I said above, the popular ones have been researched, selected, and gone through a pretty rigorous debugging process by thousands of people on hundreds of platforms.

            As such, they’re probably superior to most home-grown solutions and frameworks built to solve the same class of problems.

          • Matt Welche

            ok, hold on a second, it looks like you’ve been using the term framework very very very loosely.
            I dont know if a framework like angular should be used in the same breath as CSS “frameworks” like bootstrap, in terms of this discussion at least. Though they are simliar in concept, the performance hits from each are soooooo huge. anyway, i digress.

            Jquery is a library, not a framework, as is jquery mobile. Now, there are a ton of discussions on the interwebs about the difference between the two, but I’ve always seen a library as a loosely set collection of tools, while a framework has a strict process associated with it. A framework is a library, but a library is not necessarily a framework.
            Bootstrap qualifies as a framework (albeit a CSS framework) since it has a strict grid and its styles are set to fit with said grid. you can choose to stray from the grid and use your own, or stick with the grid and design custom styled elements, but all that time spent customizing bootstrap and removing unnecessary styles couldve been spent coding from scratch, and i’d probably still have time left.
            I myself have never been fond of frameworks like bootstrap for reasons already stated above (the BULK!!!), but i can see their utility for rapid development/prototyping.
            In my experience, the one-fits-all solution is usually not the way to go, though independent libraries (aha!) brought in sparingly when necessary can be a huge time saver. (i’ve turned to doing validation myself but ready-made javascript validation solutions were always nice)

          • http://www.isights.org/ Michael Long

            First, let me say I’m enjoying the discussion, and appreciate the give and take.

            1) Don’t need? True. Hence your original statement about pruning them down. Plus some, like jQuery Mobile or jQ UI, let you build your own version containing only the modules you require.

            2) Frameworks do rise, evolve, and disappear. So do concepts. We don’t build responsive, dynamic web sites today the same way we did 5 years ago. As such, it’s equally likely the principles upon which you based your own site or solution will need to evolve as well.

            3) Definitely true.

            4) Also true, though I’d like to add that I suspect that there’s just as many people cutting and pasting non-framework-based solutions off StackOverflow.

            And finally, I definitely didn’t mean to imply that they’re right for every project. Use the right tool for the job at hand, and all that.

            Looking forward to the next article in the series.

  • Craig Buckler

    While performance *may* not always be better in CSS3, I can guarantee the page weight will be lower. CSS3 animations require a few properties – JavaScript requires far more complex timing and positioning code.

    • http://www.joezimjs.com Joe Zimmerman

      If you’re using jQuery already, then the page weight will often be less than the CSS for simple animations because you can just say $(‘selector’).fade();

      If you’re using jQuery, though, animations will be slower.

      • Craig Buckler

        Agreed. But it’s worth examining why you’re using jQuery. Put it this way, if you have less than say – 30Kb of JS code – jQuery may be overkill.

        • http://www.joezimjs.com Joe Zimmerman

          It’s only overkill if the developers know how to use vanilla JavaScript, which few do, and few sites are allowed to only use newer browsers, so they need jQuery to cover the unknown issues that may arise. Also, jQuery can be much less overkill if you’re smart enough to build it with only the options you need.

  • http://www.dave-woods.co.uk/ Dave Woods

    Hi Craig, great list. I’d be interested to see what the hit would be on your first point though by comparing the time it takes to load a bespoke bit of code for social media buttons compared to a cached official version. Chances are that most users will have seen those buttons on another site they’ve visited and they’ll be cached by their browser. I’m not excusing the huge amount of bloat that Facebook particularly adds but it may be less of a hit actually using it for most users compared to executing our own code. I don’t know any exact figures but definitely worth an experiment :)

    • Craig Buckler

      It would be a little difficult to compare since it would depend on the user’s viewing habits, location, connection, browser etc. However, even if the script is cached, that code still needs to be executed before the remainder of the page will load. It will certainly affect performance, especially on slower devices.

  • Jim Mortenson

    Thanks for recommending some data URI generators!

  • Jingqi Xie

    Were vector graphics formatted like JSONs, and converted to SVGs by JavaScript dynamically, would the page weigh even less?

    • Craig Buckler

      Nice idea, although you’d need to offset that against the size and speed of the JS code needed to handle the conversion. Also, while XML is more verbose, it does compress exceedingly well.

      Perhaps it’d be beneficial if you have lots of complex SVGs on the page. But complex SVGs may be better as PNG or JPG anyway.

  • David Maxwell

    Great tips, Craig, but isn’t it amazing how we repeat the past? You could go back five years and find posts almost identical to these tips, just replacing framework with css or javascripting or flash or ajax. But these concepts are the same as what we used when I was doing mainframe work in the 80′s and 90′s – optimize code where ever possible.

    • Craig Buckler

      I suspect optimization is becoming a lost art. In the dial-up days we questioned every byte – I didn’t use attribute quotes for that very reason.

      Unfortunately, some developers forget that high bandwidth isn’t ubiquitous or free. Besides that, 2Mb per page is ludicrous for content websites.

      • HenriHelvetica

        Agreed that optimization is a lost art. I’ve luckily drilled that into my head since the days of ImageReady (doh!) – shift option-command-s. But as much as you do want to make page weights nice and small, I had to finish up a micro site that was music related w/ lots of YouTube embeds. It ballooned. *shrug*

  • Prosenjit Manna

    Great.