HTML5 Boilerplate and optimizing the critical rendering path by deferring scripts and styles

Previously, I constructed my website layouts using the HTML5 Boilerplate method: incorporating styles and Modernizr in the head section, jQuery (either from Google CDN or as a hosted file) along with scripts just before the closing body tag. This is an example of how it was set up:

<!DOCTYPE html>
 <!-- modernizr conditional comments here -->
 <html class="no-js">
    <head>
        <link rel="stylesheet" href="css/normalize.css">
        <link rel="stylesheet" href="css/main.css">
        <script src="js/vendor/modernizr-2.6.2.min.js"></script>
    </head>
    <body>

        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
        <script>window.jQuery || document.write('<script src="js/vendor/jquery-1.10.2.min.js"><\/script>')</script>
        <script src="js/plugins.js"></script>
        <script src="js/main.js"></script>
    </body>
</html>

However, I am now aiming to eliminate all render-blocking below-the-fold CSS and JS files as per recommendations from Google's PageSpeed Insight.

I'm looking for guidance on how to defer the loading of CSS and JS files, especially the jQuery library sourced from Google. Additionally, what steps should be taken regarding Modernizr?

Answer №1

If you want to get rid of this specific warning, follow these steps:

  • Delay the loading of all external CSS until after the page finishes loading
  • Delay the loading of all external JS until after the page finishes loading

In practical terms, here's what you need to do:

  • Separate your CSS into two categories: one for preventing the "flash of unstyled content" (FOUC) and the other for everything else
  • Do the same separation for your javascript files
  • Inline the necessary CSS and JS
  • Delay the loading of the remaining CSS and JS until after the page finishes loading

The most effective way to achieve this is by using build tools. You can utilize various Grunt tools or opt for the ant-based H5BP Build Script.

The fundamental approach to deferring loads is as follows:

(function () {
    // Load jQuery after the page has finished loading
    function loadJS() {
        var url = "https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js";
        var n = document.createElement("script");
        n.src = url;
        n.onload = loadJS1;
        document.body.appendChild(n);
    }

    // Load additional JavaScript after jQuery has been loaded.
    function loadJS1() {
        var url = "js/main.js";
        var n = document.createElement("script");
        n.src = url;
        // Add more load functions if necessary.
        //n.onload = loadJS2;
        document.body.appendChild(n);
    }

    // Check for browser support for event handling capability
    if (window.addEventListener) {
        window.addEventListener("load", loadJS, false);
    } else if (window.attachEvent) {
        window.attachEvent("onload", loadJS);
    } else {
        window.onload = loadJS;
    }
})();

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

Is it possible to trigger Material UI Dialogs from the Parent Component?

Looking for help on how to open two separate Material UI dialogs (Terms & Privacy) from their parent component, a Material UI 'simple menu'. I have already imported and nested them in the parent component, but struggling to figure out how to trig ...

Understanding the relationship between controller and view in AngularJS is crucial for building dynamic

My AngularJS script with MVC architecture is causing some issues. I suspect that there might be errors in the connection between the model, view, and controller layers. JS: var myApp = angular.module("myApp", []); //App.js myApp.controller('MainCon ...

Having trouble with the tooltip feature in Bootstrap?

I've searched high and low, including on this site! I've experimented with all sorts of code, but nothing seems to make the tooltips function in BootStrap. It's beginning to really frustrate me!! Does anyone happen to have the working js co ...

What is the process for saving an HTML document with SaveFile.js?

I'm currently implementing a save feature for my website. Utilizing the 'SaveFile.js' module from this link: 'https://github.com/eligrey/FileSaver.js/' Once the user clicks on the save button, the goal is to have the entire documen ...

What is the best method for incorporating a YouTube embedded video into an image carousel using HTML and CSS?

I'm encountering an issue with my product carousel that includes an image and a video. The image displays correctly, but when I attempt to click on the video to have it appear in the main carousel view, it doesn't function as expected. Here is a ...

Ajax is functioning properly on Internet Explorer and Safari, however it is not functioning on Firefox, Chrome, or Opera

I am attempting to retrieve modal data from an HTML page using jQuery Ajax. It seems to be functioning properly in Safari and IE 6, however I'm encountering issues in Firefox, Chrome, and Opera. Any suggestions on how to resolve this? You can find my ...

Issue with initializing MdTable in Vue Material when fetching data

After encountering a null error while trying to fetch remote data to initialize the MdTable component, I shared my issue here. The data is retrieved from a MySQL database as part of a Laravel 5.6 API project. Upon thorough investigation, it seems that the ...

Despite correctly declaring jquery-ui.js and numeric.js, the jQuery datepicker and numeric plugins are not working as expected

element, it's strange that I am not receiving any error messages. However, despite this, the jquery datepicker function and numeric plugin are not working on the intended input fields they are supposed to be linked to. This particular page is a simpl ...

What could be causing the issue of DataTables not functioning properly when using data from a new partial view?

After adding new data to a table via ajax using a partial view, the DataTable options like show entries, search, and pagination do not work with the new data. Instead, these options still display the old data. How can I refresh the datatables options with ...

Aligning SVG shapes within each other

I recently encountered a scenario where I needed to position SVG shapes in the center of each other with varying scales. For instance, placing a rectangle or triangle within the center of a circle. While I found some solutions that worked for shapes like ...

Encountering a "SyntaxError: Unexpected token '/' in... index.ejs while compiling ejs" issue following the recent npm package updates

After upgrading EJS from version 2.7.4 to 3.1.5 along with some other packages in my project, I am encountering a problem where I can no longer access any of the webpages. Instead, an error is being thrown on every page. Additionally, after the update, I s ...

Ways to dynamically fetch data by merging the response outcome with a dynamic parameter from the route in Vue.js

For the first time, I have been tasked with dynamically retrieving object parameters from the URL parameter. I am aware that I can use this.$route.params.[somelink-parameter] to obtain the URL parameter, and I understand how to retrieve and store the respo ...

Multiple instances of the removeClass function getting triggered upon completion

I need to update the class of li elements within a ul list. To achieve this, I am using the .remove method with a callback function upon completion. In my scenario, the callback function is triggered for each element that gets successfully updated, rathe ...

What could be causing my div to display a horizontal scrollbar in Firefox?

Here's a straightforward test scenario: <html> <body> <div style="border:2px solid black; overflow: auto;"> x </div> </body> </html> Upon rendering, a horizontal scrollbar appears! I was using F ...

Tips for incorporating WinBox JS into Angular applications

I've been experimenting with the WinBoxJS JavaScript library, and I'm familiar with using it in plain JS. However, I'm now attempting to integrate it into my Angular project. Can anyone guide me on how to achieve this? https://www.npmjs.com/ ...

Turn off automatic compilation for LESS styling

In my Eclipse environment, I am looking to have LESS compile only when explicitly triggered by mvn package. Currently, any changes made in my less file immediately update the CSS. How can I prevent this automatic behavior? <plugin> <groupId> ...

Modifying radio inputs to update when a state variable is altered in react.js

In my HTML, I have a div that includes 4 radio inputs, and another div with an onClick event that increments a counter. Every time I click on the div, I want the radio inputs to reload so that no input is selected. Below is the code snippet: 'use clie ...

Trouble sliding with Material UI Slider

I've encountered an issue with my Material UI slider - it doesn't slide when clicked and dragged. I followed one of the examples on the Material UI website (https://material-ui.com/components/slider/) and included an onChange function. The values ...

JavaScript and PHP open-source libraries for enabling voice chat functionality

Seeking assistance on incorporating voice-chat functionality into my website through PHP and JavaScript. Are there any open-source libraries available for this purpose? I am willing to utilize Flash if necessary, but limited to using only Flash, JavaScri ...

Is it possible to use the .focus() event on an entire form in JQuery? If so, how

Take a look at this HTML snippet: <form ....> <textarea>....</textarea <input .... /> </form> I'm trying to set up a help section that appears when the user focuses on any form element, and disappears when they lose ...