ebook img

CSS Optimization Basics PDF

40 Pages·2018·0.645 MB·English
Save to my drive
Quick download
Download
Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.

Preview CSS Optimization Basics

CSS Optimization Basics Jens Oliver Meiert Thisbookisforsaleathttp://leanpub.com/css-optimization-basics Thisversionwaspublishedon2018-04-08 ISBN978-0-9911480-5-9 ThisisaLeanpubbook.LeanpubempowersauthorsandpublisherswiththeLeanPublishing process.LeanPublishingistheactofpublishinganin-progressebookusinglightweighttoolsand manyiterationstogetreaderfeedback,pivotuntilyouhavetherightbookandbuildtractiononce youdo. ©2018JensOliverMeiert Tweet This Book! PleasehelpJensOliverMeiertbyspreadingthewordaboutthisbookonTwitter! Thesuggestedhashtagforthisbookis#cssoptim. Findoutwhatotherpeoplearesayingaboutthebookbyclickingonthislinktosearchforthis hashtagonTwitter: #cssoptim Contents Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 WhyOptimizationIsImportant . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 What’sNotCoveredbyOptimization . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 DevelopmentMindsets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 DoOneThingReally,ReallyWell . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 KnowYourNeeds . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 StayinthePresent . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 KeepItSimple . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 Automate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 OperationalOptimization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 Understandability . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 Performance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 Quality . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 Maintainability . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21 ProductionOptimization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26 Performance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26 OutputControl . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32 ToolsandReferences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33 AbouttheAuthor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36 CONTENTS 1 With special thanks to Tony Ruscoe1 for reviewing the first draft of this book, and Markus Käding forhelpwiththebookcover. 1http://ruscoe.net/ Introduction Weliveinexcitingtimes.Indeed,politically,butparticularly,andparticularlyinthecontextofthis book, technologically. The times are exciting because there has never been a greater wealth of web technologies,tools,andresourcestobuildevermoreappealingandperformantwebsitesaswellas webapps. Thetimesareexciting,too,becausetheyarechallenging.Theyarechallengingbecausethewealthof technologies,tools,andresourceshasledtoothertypesofwealth:ofcomplexity,andofconfusion. Theconfusionistobethoughtofinasenseoffocus,precisely:lackoffocus,forwithalltheoptions wehaveithasbecomelessapparentwhatwebestpayattentionto,whetherthat’swhatweshould dointhefirstplace,orhowweshould workwithwhatwehaveatourdisposal.Thatrelatesto the sites and apps we build, to the frameworks and libraries we use, and, and here we get back to why you’reholdingthisbookinyourhands,tothecodewewrite,including:theCSSwewrite. Inthisbook,then,we’lllookatwaystoimprovetheCSSwewrite.We’llgooverwhythatgenerally matters, and why each method matters. We’ll also talk about what doesn’t matter so much. For example, processors. Much of that will have to do with quality as well as craft. Both I deem important, no less of an idea of web development would I wish to promote. How to best automate suchoptimizationisagreatquestion,butfirstweneedtounderstandwhattooptimizeforexactly— and though it’s encouraged to automate as much as possible, whether optimization is to be done manuallyorautomaticallyisnotaconcernofthisbook. Why Optimization Is Important Sometimesitappearsdifficulttoanswerlegitimatequestions.Whyisoptimizationimportant?Why isbreathinguseful?Whyshouldweeat? Optimization is important because quality is important; and quality (and quality control) is importantbecause,asI’veestablishedinTheLittleBookofWebsiteQualityControl2,“withoutitwe havenorobustwayofdeterminingwhetherwhat wedoandproduceisanygood.Qualitycontrol, therefore, is a key differentiator between professional and amateur work. Consistent quality is the mark of the professional. Quality control, finally, saves time and money and sometimes nerves, particularlyinthelongrun.” That spontaneous definition, aiming at ways to check our work, doesn’t yet make the beneficiary clear: the user or customer. It’s the end user who benefits and who we want to benefit from great qualitywork. 2http://www.oreilly.com/web-platform/free/the-little-book-of-website-quality-control.csp Introduction 3 Assuch,optimization,codeoptimization,CSSoptimizationallrepresentastrivingtodeliverbetter qualityworktothebenefitofourusers,andtoourbenefitofbecominggreaterprofessionals. Optimizationhasatouchofperfectionism,butit’strulyameans,andnotanend;withoptimization weacknowledgethatourinitialworkcanbeimproved. What’s Not Covered by Optimization In this book, then, I won’t cover all things relating to CSS development these days. The reason for this is simple: Not all of this relates to optimization. And so one thing I won’t cover here are CSS preprocessors. Personally,I’ve sided withRoger Johansson3 and outlinedreasons for not using preprocessors4,butthelittlethereistooptimizethroughthemisalreadygoingtobecoveredinthis bookinotherways:forexample,throughrepeatemphasisoncodingandformattingstandards. On top of that comes that I regard it more useful to stay close to core technologies, and not get boggeddownbyabstractions,abstractionslikepreprocessors.Intheshortrunwemaybenefitfrom knowing well how to handle abstractions; but in the long run we get much greater rewards from knowingtheunderlyingsystemsandtechnologies.Andthereforewe’llfocusonstandardCSSrather thannon-standardSass,Less,Stylus,andwhatnot. The same applies to other forms of abstraction, and so we’ll look and point at CSS tools, but not discuss optimization of use of these tools, their workflows, nor how to improve those tools themselves. ⁂ The code in this book follows Google’s HTML/CSS style guide5. (For an introduction to coding guidelines and notes on the Google style guide, see The Little Book of HTML/CSS Coding Guide- lines6.) Before we begin, this is a self-published book made with little extra help. If you find mistakes in it, you have all reason to blame me, the author—but also a great opportunity to help make the book a littlebetterasacontributor(whoareallmentionedunlesstheychoosenottobenamed).Pleasefile an issue7 for every problem you find, or submit a pull request8 for specific fixes and suggestions. If youboughtthebookthroughLeanpub9 youshouldgetupdatescontainingyourandotherpeople’s fixesautomatically.(Otherwisethere’salwaystheoriginalsource10.) Thankyouforyoursupport. 3http://www.456bereastreet.com/archive/201603/why_i_dont_use_css_preprocessors/ 4https://meiert.com/en/blog/no-css-preprocessors/ 5https://google.github.io/styleguide/htmlcssguide.html 6http://www.oreilly.com/web-platform/free/little-book-html-css-coding-guidelines.csp 7https://github.com/j9t/css-optimization-basics/issues/new 8https://github.com/j9t/css-optimization-basics/pulls 9https://leanpub.com/css-optimization-basics 10https://github.com/j9t/css-optimization-basics Development Mindsets Weallknowtheadage,“Giveamanafish,andyoufeedhimforaday;teachamantofish,andyou feedhimforalifetime.”Tome,wefeeddevelopersforalifetimebyteachingandcherishingcertain mindsets. They aren’t enough, per se, but I view them as the foundation that decides where we’re headed with our work and our careers; they’re not all related to CSS optimization—that would be oddforusaswebdevelopersdealingwithmanydifferenttechnologies—,butthey’resouseful,let’s lookatthekeyones. Do One Thing Really, Really Well OutoftheGooglebook11,onewonderfulideaistodothingsreally,reallywell.ButIusedtheplural here, and Google uses singular for a reason, and for us here as web developers this thing should be webdevelopment. Todoonethingreallywellmeanstoreallykneelintowebdevelopment,topiercethroughit,tofully understand it, to practice it, to master it, to do it really well. Optimizing CSS is part of writing CSS well is part of doing web development well, and that’s why this mindset is important for us. The goaltodowebdevelopmentwellisanideathatservesusinourwork. Know Your Needs An idea occasionally forgotten, and not strictly followed, is the one of knowing our needs—of knowing our needs well. It’s actually the idea of knowing our goals, or having goals in the first place—becauseourgoalslikewisedeterminethespecificneedswehave. Knowing our goals and needs is important because evidently, it’s difficult to meet a goal when we don’tknowit,andtosatisfyaneedthatwe’reignorantof.Inthewebdevelopmentworld,thereare many goals and needs we may have: from most important goals like how to maintain our projects (from a destructive “fire and forget”12 to a very efficient process of iteration) to clearly quantified performance, and from basal needs like frameworks that cover our design ideas but don’t mean bloat13,todecisiveoneslikeautomationtools. 11https://www.google.com/about/philosophy.html 12https://meiert.com/en/blog/fire-and-forget/ 13http://www.oreilly.com/web-platform/free/book-of-html-css-frameworks.csp DevelopmentMindsets 5 Stay in the Present Without becoming overly self-helpish or even philosophical, another useful mindset for us is to also stay in the present, to stay in the now. It means both a rigid eye to get rid of, that is, archive everything—concepts, documentation, patterns, code snippets, libraries, &c.—that we don’t need and use anymore (“Know Your Needs”), and not bother prematurely coding (or planning to code) somethingthatwedon’tknowtocomewithcertainty. This mindset matters because it keeps our code base and our documentation clean, and hence significantlycontributestoourfocus(“DoOneThingReally,ReallyWell”,“KeepItSimple”). Keep It Simple The idea to keep it simple has a lazy touch, and yet it requires high skill. Keeping it simple really means focus, to know what’s important, and through that be efficient. Keeping it simple does not meantosimplydoless;itmeanstodowhatmatters. As such, keeping things simple requires that we thoroughly understand our field—the core tech- nologies, first and foremost, but everything in between and to the sides as well. And it means true economyofmotion,becausewedon’twanttoengageinsomethingthatdoesn’tneedtobedone. Asamindset,keepingitsimpleistrulygrandiose,andtheinterestedreadermaynotwanttopickup a book on minimalism but rather one about focus—my recommendation is Gary Keller’s The One Thing14. Automate Lastly,amostpowerfulmindsetaslooselyaswe’reworkingwiththemhere,istheonetoautomate. Every step of our work should, if possible, be automated. Sometimes that will be obvious—every time after we made CSS changes we run some optimization script—, sometimes that will require a bit of listening—a team member mentions how he manually updates documentation each time someone reports downtime issues—, and at other times it will be obscure—no one even knew that therewastheoptiontoautomatevisualdesignregressiontesting. Whenever we repeat something in our work, we should look into whether that repeat work can be handled through a script or tool—no matter how “hacky” the solution may be. (Personally, I workwitharecurringremindertoreviewmyworkandcheckforautomationoptions.)Andthenit requires attention, for automation is powerful. And still it doesn’t “take work away”—but liberates ustodothemoreimportantthings. 14https://www.the1thing.com/ Operational Optimization In this first section, on operational optimization, we’re going to talk about the options we have to writehigherqualityCSSwhilewe’rerightatit—inoperation.(Thesecondpartwilldealwithoptions tooptimizeforproduction,thatis,forreleaseandliveuse.) Just as it didn’t seem useful to cover preprocessors so to get a clear look at CSS itself, we’re not going to discuss documentation, as with in-file comments, nor guidelines that we can enforce in an automated fashion. Documentation is an entirely different topic that has more to do with maintenance than with optimization, and coding guidelines, as important as they are and as many of them we can set up, are often a matter of preference that doesn’t necessarily have a bearing on quality(alsosee:TheLittleBookofHTML/CSSCodingGuidelines15).We’realreadyapplyingtwoof ourmantras:keepingitsimple,andautomating. Understandability In operation, we need to make sure our work is understandable. This does not only refer to multi- personenvironmentsinwhichwe’renotaloneworkingonaproject;withconsistency,forexample, there’satleastindividualconsistency,whichmeanstowritecodeconsistentwithourselves. Thisunderstandability,asweestablishedfordocumentationandcomments,caninpartsbeachieved automatically. But some pieces, and we’ll right start with one (consistent declaration sorting), are so important and useful to learn how to do manually, that we’ll still go over them. And so we’ll firstlookatconsistencyandsimplicityasthetwopillarsformoreunderstandable,forsimplistically optimizedCSScode. Consistency Consistency in the case of code means to write and format things the same way every time. With individualor“level1”consistency16,thismeanstobeconsistentwithhowweourselveswritecode. Withcollectiveand“level2”consistency,westrivetostayconsistentwithintherealmthatwework in,aswhenwetouchthirdpartycodeandsticktotheircodestyle.Andthenthere’sinstitutionalor “level3”consistency,referringtobeingconsistentwithcodingstandardsputupbyourorganization. Consistency is a foundational part of optimization; it’s the first step of optimization. Without any sortofconsistency,anyotheroptimizationattemptsarealotharder. 15http://www.oreilly.com/web-platform/free/little-book-html-css-coding-guidelines.csp 16https://meiert.com/en/blog/consistency-levels/

See more

The list of books you might like

Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.