What causes the code following the </html> tag to be shifted in front of the </body> tag? Is there a noticeable improvement in performance

After exploring various Stack Overflow posts like this particular SO question, I came across an unconventional Google recommendation on CSS optimization. This recommendation suggested deferring CSS loading with markup that looked like this:


        <div class="blue">Hello, world!</div>
    </body>
</html>
<noscript><link rel="stylesheet" href="small.css"></noscript>

This approach seemed puzzling due to its excessive nature, confusion, invalid HTML structure, and the claim of maintaining CSS rules application order through JavaScript, although no JavaScript was present in the example. This led me to wonder:

When examining their sample code output, all content following the </html> tag moved just before </body>. So the burning question is... WHY?

  1. What prompted this shift? It seems most major browsers automatically reposition any code after </html> prior to </body>. My search for documentation or standards on this matter yielded little results.

  2. Why would Google advocate for this method? Is there a tangible performance benefit to this practice? One might assume placing it before </body> initially would suffice. (and as BoltClock's insightful explanation suggests, is there concrete evidence supporting improved performance from this technique?)

This behavior was observed in IE11, Firefox 26, Chrome 32.x, and Windows Safari 5.1.7. The inspected HTML appeared as follows:


        <div class="blue">Hello, world!</div>
        <noscript><link rel="stylesheet" href="small.css"></noscript>
    </body>
</html>

Inserting additional code post </html> rendered the same outcome.

This phenomenon evokes memories of other peculiar error-corrections, such as how browsers render <image> tags as <img> (reference)...

UPDATE: In my testing, I created this URL for NON-deferred CSS and also this URL for deferred CSS (based on my interpretation of the mentioned article)...

Answer №1

It's quite peculiar, isn't it? It's against the rules to include any elements after the closing </html> tag because the html element serves as the root of an HTML document.

  1. This is a scenario involving HTML rather than XHTML. Unlike in XHTML where errors would result in failure, browsers handling HTML will simply move anything located at the end of a document (excluding comments and whitespace) to the end of the body section and proceed as though everything is normal.

    Prior to the inception of HTML5, there were no established protocols for error correction in such circumstances due to the fact that having any elements beyond the root element was deemed invalid. With HTML5, almost all error handling scenarios are addressed in detail in section 8.2.5. Notably, if there is an unexpected token (not including DOCTYPE, comment, or </html>) during the "after body" or "after after body" insertion modes, the parser will switch to the "in body" mode to process the token, leading to its insertion into the body content per the respective insertion modes.

  2. While I cannot definitively explain why Google would endorse this practice, it could be inferred that Google values performance optimization over strict adherence to standards, especially in cases where noncompliant markup poses minimal disruption. This tendency towards risk-taking can also be observed in other facets of Google's operations, such as with Google Chrome.

    Your suggestion of placing the noscript and link elements just before the closing </body> tag aligns with how browsers and the HTML5 specification handle these situations. However, it should be noted that positioning a link element within a noscript element outside of the head section is technically not compliant with standard practices. Nevertheless, considerations like these often take a backseat to considerations of performance enhancement.

Answer №2

Simply put:

If we place any content after the closing </body> tag, it will automatically be moved inside the body section at the end. This is in accordance with HTML specifications, which dictate that all content must reside within the <body> tags. Thus, there should not be any empty spaces following </body>.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Which HTML Editing Software is Best for Me?

As a college student, I have completed multiple web development and design courses. Throughout the past few years, I have utilized various tools such as PHPStorm, Visual Studio Code, Notepad++, SublimeText3, and Atom. Although I don't necessarily hav ...

How can a Vue.js toggle button dynamically change based on the combined state of two checkboxes?

My current project involves implementing a toggle feature that allows users to enable a day and then select between AM or PM using checkboxes. One issue I'm facing is how to de-toggle the button if a user unchecks both AM and PM options. Check out t ...

Safari not supporting SVG with pointer events

When working with SVG elements (shapes), I often encounter situations where mouse clicks need to pass through transparent areas or where there is no actual shape present. To address this issue, I have utilized the css property pointer-events:none on the r ...

"Discover the magic of creating a navigation menu with jQuery toggle - let me show

Recently, I managed to create a side navigation using the target function in CSS3. However, I am curious about how I can achieve the same result using jQuery without disrupting the layout. Any assistance would be greatly appreciated. Here is the code sni ...

The Angular Material error message is indicating that the function registerInput is not defined for this._chipList, causing

Issue Description Currently, I am encountering an error when attempting to retrieve input from an <input> tag and showcase it as chips in the graphical user interface (GUI). The console displays the following error message: "TypeError: this._chipLis ...

Position an iframe in alignment

I'm working on a HTML page and I have been trying to figure out how to align an iframe at the bottom of the page so that it spans the entire width. Despite my efforts, I haven't been successful in getting the iframe to align properly at the botto ...

Struggling with transferring a hidden form value from the database to a PHP if-statement

In my database table named "Related," I have 3 columns: related_id article_id object_id This table tracks the relationships between articles and objects. I recently updated the code to only include a delete button (x). When a user clicks on this button, ...

Fade in a CSS class using jQuery

I'm attempting to incorporate a basic fadeIn() CSS effect on specific objects that are tagged with the "button" class. My goal is to have the "hoverbutton" class fade in when the object is hovered over, and then fade out when the cursor moves away fro ...

What techniques can I use to ensure that my website's layout adjusts correctly when resized?

body { padding: 0; margin: 0; font-family: 'Roboto', sans-serif; font-size: 16px; box-sizing: border-box !important; } a { display: flex; justify-content: center; align-items: center; width: 100%; height: 100%; text-decorat ...

What causes the offsetWidth attribute to be zero in an array of elements within the DOM?

I am encountering an issue with a script that sets widths for certain elements in the Dom. Specifically, when I use the code var elements = document.querySelectorAll("p.caption"), the first 12 elements display the correct offsetWidth, but the remaining hal ...

Retrieve the image information from a specified element in the Document Object Model

Is it possible to extract the image data of a DOM element using standard JavaScript or browser extensions? I'm considering scenarios where: Creating an offscreen DOM element Populating it with dynamically styled CSS content Retrieving its image dat ...

The navbar toggler icon is not displaying

<header class="container"> <div class="container pt-3 col-md-5 col-sm-5 col-xs-6 text-center"> <a href="#" class="site-logo"><img src="#"></a> <button class="navbar-toggler" type="button" data-toggle="collapse" ...

JavaScript Summation Calculation

I am currently working on calculating the sum of three scores and displaying the total as "Total:". However, I am facing an issue in dynamically updating the total whenever a score value changes. Is there a way to utilize the "onchange" event to achieve th ...

Eliminate the excess space at the bottom of rows in Materialize CSS

Having difficulty adjusting the padding between two rows in materializecss Troubles with Padding Seeking to eliminate the bottom padding. Managed to remove left and right padding with the following code: <div class="col s12 m5 white no-padding"> ...

The size of HTML select input varies among IOS, Android, and Windows devices

Does anyone know of a CSS property that can be used to tailor the styling specifically for IOS devices in order to achieve a similar look to that of windows and android?https://i.sstatic.net/VMSXb.jpg I attempted using -webkit, but unfortunately it did no ...

Tips on how to ensure the navigation menu is the same size as its child elements in the navigation menu

I'm currently designing a navigation menu that includes a child navigation menu. My goal is to have the size of the main navigation menu match that of the child navigation menu. To achieve this, I've created three hyperlink tags followed by a di ...

Following the build in Angular, it only displays the index.html file and a blank screen

According to the information on Angular's official website, running the "ng build" command should generate files in the dist folder ready for hosting. However, after running this command, the index.html file is empty except for the page title. When yo ...

Navigation website with a twist

My design features a main navigation that is rotated 90 degrees, while the sub-menu remains horizontally aligned. <div id="nav"> <ul> <li><a href="#">Woonaccessoires</a></li> ...

auto-scrolling webpage as elements come into view

Here is some jQuery code I have: $(".col-md-12").hide(); $(".button-div").hide(); $(".featurette-divider").hide(); $(".footer").hide(); $(".first").fadeIn(1000); $(".second").delay(900).fadeIn(1000); $(".third").delay(1800).fadeIn(1000); $(".fourth").dela ...

Incorporate an image into a hyperlink using CSS

I am trying to enhance my URLs by adding the same image to each of them. The code I have currently is as follows: a.linkArrow { background: transparent url('../images/abc.png') no-repeat center right; padding-right: 60px; } Here is an ...