Load scripts after page has loaded?

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?


In JQuery you could do this on document ready

$.getScript("somescript.js", function(){
   alert("Script loaded and executed.");
 });

simply you can add into that script file defer parameter

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

you can check this question as well


It is possible. I was doing a similar thing in an AJAX intensive site, but I was loading the Google Charts API. Here is the code I used to load the Google Charts API when a button was clicked on the page.

function loadGoogleChartsAPI() {
    var script = document.createElement("script");
    // This script has a callback function that will run when the script has
    // finished loading.
    script.src = "http://www.google.com/jsapi?callback=loadGraphs";
    script.type = "text/javascript";
    document.getElementsByTagName("head")[0].appendChild(script);
}

function loadGraphs() {
    // Add callback function here.
}

This uses a callback function that will run when the script has loaded.


No one mentioned these?

$(window).load(function(){
    // do something 
});

or

$(window).bind("load", function() {
   // do something
});