Categories
JavaScript Answers

How to Load Scripts After the Page has Loaded in JavaScript?

Spread the love

Sometimes, we want to load scripts after the page has loaded in JavaScript.

In this article, we’ll look at how to load scripts after the page has loaded in JavaScript.

Load Scripts After the Page has Loaded in JavaScript

To load scripts after the page has loaded in JavaScript, we can call the jQuery getScript method after the document has been loaded.

We can also listen to the DOMContentLoaded event with plain JavaScript.

For instance, we can write:

$(document).ready(() => {  
  $.getScript("https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js", () => {  
    console.log("Script loaded and executed.");  
  });  
})

We call getScript in the $(document).ready callback so that it’s run only when the DOM is loaded.

To do the same thing with plain JavaScript, we can listen to the DOMContentLoaded event.

To do this, we write:

document.addEventListener('DOMContentLoaded', () => {  
  const script = document.createElement('script');  
  script.src = 'https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js';  
  document.body.appendChild(script);  
});

We call document.addEventListener to add the event listener.

Then in the event listener, we call document.createElement to create the script element.

And we set the src attribute by setting the src property.

Finally, we call document.body.appendChild to append it to the body.

Conclusion

To load scripts after the page has loaded in JavaScript, we can call the jQuery getScript method after the document has been loaded.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *