Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load scripts after page has loaded?

Tags:

javascript

Is it possible to load certain scripts like

<script type="text/javascript" src="somescript.js"></script> 

when the rest of the page has loaded?

Imagine I have a few larger script files like this that are not needed when the page is loaded. E.g. I'm using the Google Maps API that is only used when a button is clicked (so not on page load).

Is it possible to load the rest of the page first, before processing all those script tags in my head?

like image 236
matt Avatar asked Mar 30 '11 19:03

matt


People also ask

Which event would you use to start a script after a page has been fully loaded by the browser?

The onload event occurs when an object has been loaded. onload is most often used within the <body> element to execute a script once a web page has completely loaded all content (including images, script files, CSS files, etc.).


2 Answers

In JQuery you could do this on document ready

$.getScript("somescript.js", function(){    alert("Script loaded and executed.");  }); 
like image 79
slandau Avatar answered Oct 08 '22 03:10

slandau


simply you can add into that script file defer parameter

<script src="pathToJs" defer></script> 

you can check this question as well

like image 37
nikoss Avatar answered Oct 08 '22 02:10

nikoss