What is the reason behind Google Plus loading CSS using XHR and then appending it to a <style> tag instead of simply using <link>?

I recently examined the Javascripts used in the new Google Plus platform and discovered an interesting approach to loading CSS. Instead of utilizing <link> tags to reference a CSS file, Google Plus employs XHR to retrieve the CSS content from a separate file. It then dynamically creates a <style> element and injects the CSS content into it.

What might be the rationale behind Google's decision to implement this method for loading CSS?

Evidence:

D = function(a) {
  var b = document.createElement("style");
  b.type = "text/css";
  document.getElementsByTagName("head")[0].appendChild(b);
  b.styleSheet ? b.styleSheet.cssText = a : b.appendChild(document.createTextNode(a))
};

var ia = function(a, b) {
  if(4 == b.readyState) {
    var d = window;
    $("xcl");
    b.onreadystatechange = k;
    var c = b.status;
    if(400 > c) {
      try {
        var e = b.getResponseHeader("X-Framework-CSS-Blocks"), f = b.responseText;
        if(e) {
          for(var e = e.split(","), g = c = 0;g < e.length;g++) {
            var V = Number(e[g]);
            D(f.substr(c, V));
            c += V
          }
          c < f.length && D(f.substr(c))
        }else {
          D(f), ha() && C("css", a, d.OZ_lang, "nooffsets")
        }
        d.setTimeout(function() {
          for(var b = i, c = 0, e = document.styleSheets.length;c < e;c++) {
            var g = document.styleSheets[c], g = g.cssRules || g.rules;
            0 < g.length && "sentinel" == g[g.length - 1].selectorText && (b = !0)
          }
          b || C("css", a, d.OZ_lang, "truncated." + f.length)
        }, 1E3)
      }catch(W) {
        throw d.console && d.console.warn(W), C("css", a, d.OZ_lang, "error"), W;
      }
    }else {
      C("css", a, d.OZ_lang, "status." + c)
    }
    $("xcr")
  }
}, ja = function() {
  var a = window.OZ_cssUrl;
  $("xcs");
  var b = ga();
  b.open("GET", a, !0);
  b.onreadystatechange = function() {
    ia(a, b)
  };
  b.send(h)
}

window.OZ_cssUrl && ja()

Answer №1

When it comes to loading CSS dynamically, using link tags can be unreliable due to inconsistent browser support for the load and error events. Although dynamic link tags do work, there is uncertainty about when the CSS actually loads. Additionally, since they are async, you may encounter issues with the style cascade order.

An alternative approach is to load CSS via AJAX as a string, taking advantage of its reliable success and fail events. Once the string is received, it can be appended to a style tag, allowing for greater control over when the CSS is loaded.

Although this method sacrifices cross-domain CSS functionality, it provides more certainty regarding the timing of CSS loading.

Answer №2

In a recent response by Mark Knichel, a skilled member of the Google+ infrastructure team, he shared some insights.

"One interesting thing to note is how we handle loading our CSS using XHR instead of a typical style tag. This decision wasn't made for optimization purposes, but rather due to hitting Internet Explorer's maximum CSS selector limit per stylesheet!"

To delve deeper into this topic, visit

Answer №3

Recent advancements in web development have shown a significant performance boost when a google developer switched from XHR to traditional <link> inclusion.

SPDY enabled browsers experienced a notable decrease in latency as a result. Chrome 27 demonstrated a 4x improvement in speed at the median, and 5x at the 25th percentile. Firefox 21 saw a 5x increase in speed at the median, and 8x at the 25th percentile. There was no significant impact at the 99th percentile.

Source:

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

Upon transmitting the information to the server, an error message pops up saying 'Uncaught TypeError: Illegal invocation'

I'm encountering an issue with sending an ajax request in my php-script. The jquery script I'm using selects certain fields from a form and sends them as arguments to a jquery function. However, upon sending the data to the server, I receive the ...

Automatically logging in to a website using an AngularJS form

I am struggling with autologin to a website that has an authentication form built with Angular JS. The form structure looks like this: <form name="loginForm" class="login-form ng-pristine ng-invalid ng-invalid-required"> <div class="tight-fo ...

Tips on transferring key values when inputText changes in ReactJs using TypeScript

I have implemented a switch case for comparing object keys with strings in the following code snippet: import { TextField, Button } from "@material-ui/core"; import React, { Component, ReactNode } from "react"; import classes from "./Contact.module.scss" ...

Leveraging jQuery to extract a key-value pair and assign it to a new property by

I'm struggling with extracting a value from a key-value pair and inserting it into the rel property of an anchor tag. Even though I try to split the code and place the value correctly, it doesn't seem to work as expected. Instead of applying the ...

Tips on reversing a numeric value with scientific notation in nodeJS

Exploring the optimal method to reverse an integer (positive and negative) in NodeJS 12 without the need to convert the number to a string. This solution should also accommodate numbers written in scientific notation such as 1e+10, which represents 10000 ...

Animating SVG while scrolling on a one-page website

Is there a way to incorporate SVG animation scrolling in a single page website? I am inspired by websites like and . The first one stands out to me because the animation is controlled by scrollup and scrolldown actions. I haven't written any of my S ...

What steps do I need to take to develop a syntax similar to Vue.js using only plain JavaScript?

<div id=""> <span>{{msg}}</span> </div> Assume that {{msg}} is a variable in JavaScript. Now, I aim to locate the parent tag of {{msg}} and replace its content with a new value using innerHTML, where {{msg}} serves as an identi ...

What steps can be taken to troubleshoot a jQuery / JavaScript conflict?

I am facing an issue with my web page, which includes two WebUsercontrols(.ascx): one for a slide show and the other for FullCalendar. When running each user control separately, they work fine. However, when both are included on the same page, a script con ...

Received a String instead of an Object while attempting to parse JSON data

Currently, my goal is to parse a JSON string using jQuery var parsedData = $.parseJSON('{"graph_info": "{}"}'); I assumed that typeof(parsedData.graph_data) would be an Object but surprisingly it is returning as a string. Can someone guide me o ...

What is the best way to display multiple divs in a single location?

I am facing an issue with displaying different text on mouseover for three buttons. I successfully implemented it for one button, but when I added the other two, it stopped working. Here is the code I used for the first button: Using jQuery- document.get ...

React Native Issue: Missing propType for native property RCTView.maxHeight

Upon upgrading to RN 0.30, I encountered the error message below even when trying to build the most basic app: react-native init AwesomeProject react-native run-ios What's peculiar is that the warnings include components BlurView, VibrancyView, an ...

Discovering the div element with a corresponding data attribute and subsequently removing a class from it

My code attempt doesn't seem to be functioning as expected: $('container').find("[data-slider='" + one + "']").removeClass('hidden'); This is the complete function enclosed within a document ready function: $("#service ...

Conditionally Changing the Display Attribute of an HTML Button based on the Result of a jQuery Get() Request

Hello there! Recently, I encountered an interesting problem while working on a browser extension that I have been tinkering with for quite some time. The issue revolves around the dilemma of showing or hiding a specific button based on an 'if stateme ...

The error message in Express points to module.js line 550 and states that the module cannot be

I am currently in the process of setting up a basic express application using the code below: const express = require('express'); const app = express() const bodyParser = require('body-parser'); const cookieParser = require('cooki ...

Struggling to decipher intricate JSON tables for React components? Let us assist you in navigating through complex

Desired Output //JSON "servers": [ { "name": "virtztp01-os1-cntl2", "ipv4Address": "10.189.147.70", "ipv6Address": "2000:::00", ...

Steps for implementing drag-and-drop feature for a div in a template

I am looking to implement draggable functionality on a div element dynamically. The unique id for the div is generated using the code snippet below: var Exp=0; view.renderFunction = function(id1){ var id= id1 + Exp++; $("#"+id).draggable(); }; In my ...

retrieve the documents that correspond to a specific string in mongoose

Currently, I am working on integrating a search feature into a MERN stack application. The idea is to utilize the searchWord extracted from req.params.searchWord and fetch results containing that specific searchWord. Although my existing code serves its p ...

Is @babel the solution to transpile Array.prototype.flat?

I accidentally caused a backward compatibility issue in my React application by utilizing Array.prototype.flat. I was quite surprised that this problem persisted even after transpiling - I had assumed it would generate es2015-compatible code. Is there a w ...

Issue with the appearance of the footer in my Wordpress template

After creating a WordPress template, I noticed that the footer is not extending to 100% width as expected. Check out the page here Any suggestions on why this might be happening? Could it be due to a missing closing div tag somewhere in the code? Thank ...

Is the Pure CSS hide/show technique using radio buttons causing a challenge with parent and descendant elements?

Exploring a CSS Show/Hide functionality using radio buttons is my current challenge. The snippet below demonstrates how smoothly it works. .refusal, .acceptance { display: none; } input#refusal:checked~.refusal { display: block; } input#acceptanc ...