External CSS vs inline style performance difference?
Asked Answered
E

10

110

A friend of mine said that using <div style=""></div> instead of compressed css file put as link href at the head section gives some performance boost. Is that true?

Epigynous answered 27/11, 2011 at 8:10 Comment(4)
As far as I know, they're (roughly) the same, but I can't verify that.Uzziel
This might shed some light : mathiasbynens.be/notes/inline-vs-separate-fileVested
It would have to be a significant performance boost to deal with the maintenance nightmares that are inline styles. So far I've seen no eviidence of thatt.Mufti
For older versions of IE the performance boost is VERY significant. I've seen HTML tables behave like glue with CSS styling.Infelicity
L
122

The performance boost that your friend mentioned is probably too trivial compared to the amount of performance boost (through other factors) using a CSS file.

Using the style attribute, the browser only paints the rule for that particular element, which in this case is the <div> element. This reduces the amount of look up time for the CSS engine to find which elements match the CSS selector (e.g. a.hover or #someContainer li).

However, putting styling at element level would mean that you cannot cache the CSS style rules separately. Usually putting styles in CSS files would allow the caching to be done, thus reducing the amount of load from the server each time you load a page.

Putting style rules at the element level will also make you lose track of what elements are styled what way. It might also backfire the performance boost of painting a particular element where you can repaint multiple elements together. Using CSS files separates the CSS from HTML, and thus allows you to make sure that your styles are correct and it's easier to modify later on.

Therefore if you look at the comparison, you would see that using a CSS file has much more benefit than styling at element level.

Not to forget when you have an external CSS stylesheet file, your browser can cache the file which increases your application efficiency!

Locular answered 27/11, 2011 at 8:20 Comment(9)
Can you provide any statistics with chrome profiler? CPU & GPU are costly on mobile and tablet, where battery consumption is huge cost. I think there is a trade off. And what is the benefit of Cache? Browser will have to compute style for current element and resolving styles will be more costly if there are many rules.Sex
Note that all the disadvantages related to maintenance disappear when there is an engine that inlines the styles before sending to clientsConvexity
The disadvantages related to maintenance also disappear when using React + Radium.Lightface
@AjaxLeung no doubt what you and Shaham had said is is true. This answer was written in 2011, when most modern tools were not available yet.Locular
Yes. I was simply adding the comment for those seeing this answer today and beyond.Lightface
about the caching issue. Don't html files get cached? And if they do, wouldn't the inline CSS inside them get cached with them too?Ordure
Maybe at that moment this response was accurate. At this time, try Google SpeedPage to confirm otherwise. For PHP scripts, for example, stylesheets are selected, minified and previously included (include()) in the page. So the page scripts, those that the server compiles and delivers to the browser, are never modified directly. You only work with independent stylesheets. In my experience, to achieve a 100/100 rating in PageSpeed you usually have to use inline styles.Mysia
Many web applications use webpack style-loader (which produce inline style). Should we stop to use style-loader based on this answer?Buerger
Also Note, html pages can be cached as well.Reformer
S
9

The page will load faster if you use inline styles vs style sheets. In some cases must faster.

When you use a style sheet using href it requires another request to the server, then the parsing of the file after response. With inline styles there is none of that, just direct parsing.

If a client has slow internet then that single request could be very slow leaving the page style-less until the style sheet get delivered. Again, if it were inline there would be no delay at all.

The only reason we use style sheets is to be organised. There are times when they are not needed, so inline styles or in-document style sheets suffice.

Sheena answered 12/4, 2016 at 15:47 Comment(5)
This answer completely ignores browser caching. Stylesheets allow for only requesting the styles once and caching them, decreasing the amount of content sent over the wire.Winser
This answer also ignores the fact that inline styles make the HTML file larger. Potentially, especially when using repeated inline styling, a number of times larger than CSS file. By the way, browsers can load multiple files in parallel (and cache them like mentioned above).Tortoise
@Winser but the HTML page will hopefully be cached (304), so caching isn't really ignored.Atomicity
@JanVanderHaegen The initial load time might be faster if you don't have to include CSS that isn't used on the particular page you are visiting. If you put all of your CSS in external files then the HTML file is smaller, true, but the external CSS file might be larger. Pros and cons.Atomicity
@GeekOnCoffee's comment completely ignores browser caching... of JS and HTML files tooGraticule
B
6

It's not an easy question to answer, because the perfomance in this case depends on many factors (complexity of CSS selectors, document size, etc.). However, if we take an isolated case, then we can see that CSS class is in general faster than inline style:
Inline style vs CSS class

Bipartisan answered 30/9, 2013 at 10:46 Comment(6)
Pretty sure this is testing the speed at which the node class or style attribute is changed rather than the speed at which the style is applied which is what the question is askingChaves
@Chaves What do you mean by the "speed at which the style is applied"? Can you provide a test which measures this speed? If you take a look at the test code, you will see that page reflow occurs on each iteration, which means that test covers not only class/attribute modification, but also actual impact on the page.Bipartisan
It maybe includes the time to add the style but it also adds time. What if the document already had the class test or an inline style without JS needing to add it. I'm getting at the speed for the CSS to be resolved in either case and (I might be wrong) but I don't think this test just does that, I think it does extra work.Chaves
@Chaves This test ignores possible footprint of loading CSS by browser and processing it. I mentioned in my answer that this is an isolated case. It just measures performance of applying styles using different ways (inline vs external). This is what typical web applications do today - change HTML document from JavaScript without page reload.Bipartisan
Ah OK, I was referring to non-dynamically added stylesChaves
@Bipartisan link is now deadBridges
R
3

Well it can but the reason for the linked or external style sheet is so it can be cached in the browser especially when your using the same div in multiple pages for the site. This means the browser only has to load the style sheet once instead of having to reload the code every time the browser reloads page. It also makes for cleaner code which makes any changes or debugging easier.

Ries answered 27/11, 2011 at 8:16 Comment(4)
It's the essence of caching mechanism. It doesn't need proofs.Meares
It can be "cashed" doesn't mean is "cashed"; and "essences" are not facts.Lockwood
Guys, it's not duke nukem era anymore, we don't cash people. Cache on the other hand...Tuck
The caching argument doesn't hold for single page applications, which generally load everything once up front and generate pages on the fly.Midweek
C
2

THE TRUTH IS 'YES'

There is a huge difference. Especially when you are automating user interface. Try the following code. I use IE10 and notepad to develop. I am learning as I go and make tests this is a shortened version test. (there maybe errors as I reduced the code to show your answer)

Click on the image you reference and read the alert messages. HINT: Save this file the save again as an edit before editing (testing).

Best wishes, Don

<!DOCTYPE html>
  <head>
    <style>
      div.grid
        {
        width:180px;
        height:42px;
        border:none;
        }
      img
        {
        width:50px;
        height:50px;
        margin:2px;
        float:left;
        border: 1px solid red;
        }
    </style>
    <script>
      function handleSelect(xId)
        {
        //
        // TESTPOINT
        alert("TESTPOINT\r>Grid: " + xId);
        //
        // GET BORDER COLOR
        // NOTE: An empty or blank value when you can see a border means the tag itself does not
        //            have 'border properties' (style="border: 2px{width} solid{style} green{color}").
        //            although there can be a border detailed via css local or external or via code (script).
        //            If the 'border properties' are returned then they were setup at the tag as
        //            above or the 'border properties' were updated by script code not css code.
        //            If the 'border properties' are NOT returned then they were setup via css.
        //            Thus, since everything seems to be heading toward edit on the fly (live) then css is NOT the way to go (learning).
        // HINT: Margin property is also not readable if set via css. Most likely all the properties values are the same way.
        //           Thus, setting the property values of a tag should be set at the tag control.
        // (works) cBorder=document.getElementById(xId).style.borderWidth;
        // (works) cBorder=document.getElementById(xId).style.borderStyle;
        // (works) cBorder=document.getElementById(xId).style.borderColor;
        // (works) cBorder=document.getElementById(xId).style.border;
        //cBorder=document.getElementById(xId).style.border;
        cBorder=document.getElementById(xId).style.margin;
        alert("TESTPOINT\r>Grid: " + xId + "\r>Border: " + cBorder);
        //
        // SELECT IMAGE
        document.getElementById(xId).style.margin="1px";
        document.getElementById(xId).style.border="2px solid gold";
        document.getElementById(xId).innerHTML=xId;
        alert("TESTPOINT\r>Grid: " + xId + "\r>Border: " + cBorder + "\r>[set border color gold]");
        //
        // GET BORDER COLOR
        //var cBorder=document.getElementById(xId).style.border-Color;  //Error
        //var cBorder=document.getElementById(xId).style.border-color;  //Error
        //var cBorder=document.getElementById(xId).style.borderColor;   //Error
        //var cBorder=document.getElementById(xId).style.bordercolor;   //Undefined
        cBorder=document.getElementById(xId).style.border;      //Empty
        alert("TESTPOINT\r>Grid: " + xId + "\r>Border: " + cBorder + "\r>[set border color gold]" + "\r>Border: " + cBorder);
        }
    </script>
  </head>

  <body>
    <div class="grid">
      <img style="border: 2px solid green" id="R0C0" src="someimage.bmp" onclick="handleSelect(id)">
      <img style="border: 2px solid blue" id="R0C1" src="someimage.bmp" onclick="handleSelect(id)">
      <img style="border: 2px solid purple" id="R0C2" src="someimage.bmp" onclick="handleSelect(id)">
    </div>
    <div class="grid">
      <img id="R1C0" src="someimage.bmp" onclick="handleSelect(id)">
      <img id="R1C1" src="someimage.bmp" onclick="handleSelect(id)">
      <img id="R1C2" src="someimage.bmp" onclick="handleSelect(id)">
    </div>
    <div class="grid">
      <img id="R2C0" src="someimage.bmp" onclick="handleSelect(id)">
      <img id="R2C1" src="someimage.bmp" onclick="handleSelect(id)">
      <img id="R2C2" src="someimage.bmp" onclick="handleSelect(id)">
    </div>
  </body>
</html>
Centralism answered 20/8, 2013 at 22:18 Comment(1)
I use IE10 and notepad to develop. ?Towel
M
2

There is no fixed answer in my opinion.

An inline CSS will load faster if the CSS content size downloads faster than your server would respond to an external CSS file request (considering DNS time, server latency, etc).

For normal size CSS I would inline them in the page, for something over 15-20KB I would probably put it in an external file and make sure it can be cached.

I am sure there are many other considerations I am missing now, but there is no fixed answer for inline vs external.

Mahala answered 23/2, 2020 at 23:11 Comment(0)
L
0

Definitely yes, as there's no server requests the css is loaded and rendered together with the html, making it much faster.

But I recommend using internal css instead of inline css, using the <style> inside the <head> tag with your core styles needed to display the homepage and then loads external CSS files

Lasko answered 29/10, 2021 at 20:16 Comment(2)
Can you explain this recommendation further?Andi
yes ... inside head use <style> tag to avoid http request and write your core css such as preloading overlay, skeleton screens, etc ... this way as soon as server responds will paint something on screen instead of blank page. EX: <html><head><style>/* core css */</style></head><body><!-- content --><link href="external-stylesheet.css"/><script></script></body></html>Lasko
A
0

It's 2024, and I decided to find out for myself if inline styles are faster than CSS.

I did an experiment using my own website. I created a version that used inline styles (the control) and a version that used a linked stylesheet.

When it came to putting pixels on the screen, inline styles consistently outperformed CSS (even when it was cached). This was more significant on low-powered devices or when the CSS wasn't cached and the network was throttled.

While inline styles increased the size of my HTML and JavaScript bundle, the difference was insignificant after compression. In fact, inline styles resulted in the least amount of bytes total for the browser to download, at least on the first page visit before the CSS is cached.

For more information, you can read my blog post Are Inline Styles Faster than CSS?.

This experiment primarily focused on load performance. More experimentation is required to know if there is a significant difference between inline styles and CSS when it comes to repainting for interactive websites.

Akbar answered 6/4 at 20:32 Comment(0)
K
-1

Using external style sheets is definitely a better option because it will help you to remember the style you have applied on the div(s). It reduces the time of loading the page because the lesser the HTML code the faster it will load.

But in some cases you might have to change some property of a particular div then the inline style is the best option. And truly speaking, one or two inline style won't make any change the time of loading the page.

There is another option of internal style sheet but it is used only when you have a single page website like if you are making a template. This is because you have to write CSS in every HTML page

Keyte answered 24/10, 2013 at 12:59 Comment(1)
less html doesn't mean less load, It's differently a factor but the first contentful paint needs your CSS to be loaded as well.Zwart
P
-2

I prefer using inline CSS over external CSS where there are multiple small CSS files for every other element or image. No point in downloading several CSS files with merely 5-10 lines of code in each. If your element contains properties such as hover, active, checked etc. you're then supposed to use an external CSS file as it will avoid complicating your development process.

Passing answered 12/10, 2018 at 10:5 Comment(1)
That makes maintaining extremely difficult. CSS, JS files should be cached on your user's browser by default.Onfre

© 2022 - 2024 — McMap. All rights reserved.