How to defer non-critical CSS and JavaScript files

Deferring non-critical CSS and JavaScript files can help to improve the loading speed of your website. This is because non-critical files are not necessary for the initial rendering of your website, so they can be loaded after the page has started to load.

There are a few ways to defer non-critical CSS and JavaScript files. Here are a few of the most common methods:

  • Use the defer attribute: The defer attribute tells the browser to defer the loading of a file until after the page has started to load. To use the defer attribute, add the following code to the head section of your HTML document:
HTML
<script defer src="script.js"></script>
  • Use the async attribute: The async attribute tells the browser to load a file asynchronously, which means that it can be loaded in parallel with other files. To use the async attribute, add the following code to the head section of your HTML document:
HTML
<script async src="script.js"></script>
  • Use a content delivery network (CDN): A content delivery network (CDN) is a network of servers that are distributed around the world. When a user visits your website, the CDN will deliver the content from the server that is closest to the user. This can help to improve the loading speed of your website for users around the world.

To use a CDN, you will need to sign up for a CDN provider. There are a number of CDN providers available, such as Cloudflare, Amazon CloudFront, and Google Cloud CDN. Once you have signed up for a CDN provider, you will need to add your website’s content to the CDN. This can usually be done by adding a few lines of code to your website’s code.

Once your website’s content has been added to the CDN, the CDN will start delivering your website’s content to users around the world. This can help to improve the loading speed of your website for users around the world.

Here are some additional tips for deferring non-critical CSS and JavaScript files:

  • Only defer files that are not critical to the loading of your website. Not all files need to be deferred. For example, you may not need to defer files that are used for styling or animations.
  • Use a minifier to reduce the size of your files. Minification removes unnecessary whitespace and comments from your files, which can make them smaller and faster to download.
  • Test your website after deferring files. Make sure that your website still works correctly after deferring files. You don’t want to defer files so much that they break your website.

By following these tips, you can defer non-critical CSS and JavaScript files and improve the loading speed of your website.