matt
matt

Reputation: 44293

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?

Upvotes: 49

Views: 104065

Answers (10)

Andrej
Andrej

Reputation: 707

Please see my code. The onload event will occur when the script has finished loading. Or the onerror event will occur.

function loadJavaScript() {
    var script = document.createElement("script");
    script.src = "javaScript.js";
    script.type = "text/javascript";
    script.onload = function () {
        console.log('script was loaded successfully');
    }
    script.onerror = function (e) {
        console.error('script.onerror');
    }
    document.getElementsByTagName("head")[0].appendChild(script);
}

Thanks to answer.

Also see my code of the load of the script.

Upvotes: 5

danijar
danijar

Reputation: 34175

To just allow the page to show before your script is loaded, use the async attribute:

<script src="//url/to/script.js" async></script>

To hide the loading spinner in the browser, append the script tag after the page finished loading:

<script>
document.addEventListener('DOMContentLoaded', function() {
  var script = document.createElement('script');
  script.src = '//url/to/script.js';
  document.getElementsByTagName('body')[0].appendChild(script);
});
</script>

Upvotes: 2

Winfield Trail
Winfield Trail

Reputation: 5695

Yep, that's completely possible. Add an onLoad="foo();" event to your <body> tag and have it invoke your scripts. You'll need to wrap your external JS in a function and do something like:

//EXTERNAL JS (jsstuff.js)

function Mojo() {
    document.getElementById('snacks').style.visibility = "visible";
    alert("we are victorious!");
}

//YOUR HTML

<html>
    <head>
        <script type='text/javascript'></script>
    </head>
    <body onLoad='Mojo();'>
        <div id='snacks'>
            <img src='bigdarnimage.png'>
        </div>
    </body>
</html>

Upvotes: 0

nikoss
nikoss

Reputation: 3668

simply you can add into that script file defer parameter

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

you can check this question as well

Upvotes: 20

Dan Linh
Dan Linh

Reputation: 139

$(document).ready(function() {
    var ss = document.createElement("script");
    ss.src = "somescript.js";
    ss.type = "text/javascript";
    document.getElementsByTagName("head")[0].appendChild(ss);
});

Upvotes: 9

smfoote
smfoote

Reputation: 5609

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.

Upvotes: 16

laike9m
laike9m

Reputation: 19318

No one mentioned these?

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

or

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

Upvotes: 9

slandau
slandau

Reputation: 24052

In JQuery you could do this on document ready

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

Upvotes: 52

Atanas Korchev
Atanas Korchev

Reputation: 30661

Yes, this is possible by dynamically injecting the JavaScript files from code. There are lots of libraries which you can use:RequireJS, HeadJS etc. Recently I found this document which compares lots of JavaScript loader libraries.

Upvotes: 1

Flavio CF Oliveira
Flavio CF Oliveira

Reputation: 5285

use the getScript method of jquery! or try simply to put this script on the end of the page?

Upvotes: 1

Related Questions