How To Add Defer And Preload in script and link tags in Nuxtjs Application


Here in this article, we will see how to add defer and preload in link and script tags in our nuxtjs application.

The preload in the link tag and defer in the script tag helps to improve the page rendering speed and optimize our website overall. It is also the best SEO practice for your website. This also helps us to load any third-party script in our nuxt aplication globally without any issue with the performance.

Let's learn about it in detail and also how to add these values in our link and script tags.

What is LinkTypes: preload?

The preload value of the link element helps to fetch and cache the CSS style property or script link that the page will need few seconds after loading the page. It helps to load the webpage quicker. The preload value must be written in the rel attribute of the < link > tag and in the < head > tag

  <link rel="preload" href="style.css" as="style">
  <link rel="preload" href="main.js" as="script">

What is javascript defer?

The defer value indicates executing the script after the page has been rendered. It works with external scripts only we have to specify it in the src attribute in the script tag. It tells the browser to continue parsing the webpage and execute the script tag after the HTML document is compeletely parsed.

Why it is helpful? it is helpful because sometimes the application or the webpage consumes more memory while executing lots of script tags together, and it causes some performance issues and the page loading gets really slow. So we use the defer attribute value in the < script > tag to improve the performance of the webpage.

<script src = "main.js" defer>  

Now let's see how we can add the preload and defer value in our nuxtjs application

In nuxtjs application, open your nuxt.config.js file.

In the link array add the preload value to the rel attribute as shown below:

head:{
    link: [
    { rel: 'preload', as:'style', href: 'https://fonts.googleapis.com/css2?family=Rubik:wght@400;600&display=swap'},
  ],
}

And to add the defer value we have to set it to true in the script array of the nuxt.config.js file:

head:{
 script:[{ src: 'bootstrap.min.js',  defer: true }] 
}

By using the defer in the < script > tag we can load any third-party script globally in our nuxt application.


💾 Recommended Articles