Ashkan Mobayen Khiabani
Ashkan Mobayen Khiabani

Reputation: 34180

load jquery after the page is fully loaded

I'm looking for a way to load jquery after the page is fully loaded.
well there are lots of questions and answers about it in here, but all describe how to run a script that needs jquery after either page or jquery fully loaded.
What I'm looking for is to load the page and then call jquery and after the jquery is loaded call the functions. something like:

document.onload=function(){
   var fileref=document.createElement('script');
  fileref.setAttribute("type","text/javascript");
  fileref.setAttribute("src", 'http://code.jquery.com/jquery-1.7.2.min.js');
  //Here I need an event to know that jquery is 
  //loaded to run stuff that needs jquery
}

Upvotes: 15

Views: 111905

Answers (11)

Ashkan Mobayen Khiabani
Ashkan Mobayen Khiabani

Reputation: 34180

I have asked this question more than 6 years ago, and any answers I got had some flaws. Later I myself worked out a solution that I have been using for years since then. Now that I came across my own question again and I saw that it has many views, I'd like to share it because I think it may help others.

This problem mainly occurs on Master-Detail type of pages (can be old .master and .aspx pages) or (layout and views in asp.net) or any similar situation maybe on other web development languages, however always there is a master-detail pattern involved.

For the solution, I just add an array at the beginning of my page:

<script>var after = [];</script>

any function that requires jQuery or any other script that would run after this section, instead of running it, I just push it to this array:

after.push(function(){
     // code that requires scripts that will load later,
     //might be for example a jQuery selector or ...
}); 

and then at the very end of the page, right before closing the body tag (of course scripts are loaded by now) I run all the functions inside the (here named) after array:

<script>for(var i=0;i<after.length;i++)after[i]();</script>
</body>

I find this way very easy, simple and flawless.

Upvotes: 0

Drachenfels
Drachenfels

Reputation: 3294

For your problem, the solution might be to attach CDN hosted by google with certain library:

https://developers.google.com/speed/libraries/devguide

Also, you can add this at the bottom of page (just before </body>):

<script type="text/javascript">
(function() {
    var script = document.createElement('script')
    script.setAttribute("type", "text/javascript")
    script.setAttribute("src", "https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js")
    document.getElementsByTagName("head")[0].appendChild(script)
})();
</script>

However, this is risky in my opinion. You have an asynchronous call for jquery, thus your jquery has to wait until it loads (ie. $(document).ready won't work in this case). So my answer would be: use a CDN like google suggests; put your javascript on the bottom just before </body>; and, ignore flags from profilers.

Upvotes: 7

Mr.Turtle
Mr.Turtle

Reputation: 3090

Try this:

 $(document).ready(function() {
// When the document is ready
// Do something  
});

Upvotes: 23

umar_
umar_

Reputation: 491

You can also use:

$(window).bind("load", function() { 
    // Your code here.
});

Upvotes: 8

Josiah
Josiah

Reputation: 3178

If you're trying to avoid loading jquery until your content has been loaded, the best way is to simply put the reference to it in the bottom of your page, like many other answers have said.

General tips on Jquery usage:

  1. Use a CDN. This way, your site can use the cached version a user likely has on their computer. The // at the beginning allows it to be called (and use the same resource) whether it's http or https. Example:

    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Using a CDN has a couple of big benefits: it makes it more likely that users have it cached from another site, so there will be no download (and no render-blocking). Further, CDNs use the closest, fastest connection available, meaning that if they do need to load it, it will probably be faster than connecting to your server. More info from Google.

  1. Put scripts at the bottom. Move as much of your js to the bottom of the page as possible. I use php to include a file with all my JS resources below the footer.

  2. If you're using a template system, you may need to have javascript spread throughout the html output. If you're using jquery in scripts that get called as the page renders, this will cause errors. To have your scripts wait until jquery is loaded, put them into

    window.onload() = function () { //... your js that isn't called by user interaction ... }

This will prevent errors but still run before user interaction and without timers.

Of course, if jquery is cached, it won't matter too much where you put it, except to page speed tools that will tell you you're blocking rendering.

Upvotes: 0

Irvin Dominin
Irvin Dominin

Reputation: 30993

You can try using your function and using a timeout waiting until the jQuery object is loaded

Code:

document.onload=function(){
    var fileref=document.createElement('script');
    fileref.setAttribute("type","text/javascript");
    fileref.setAttribute("src", 'http://code.jquery.com/jquery-1.7.2.min.js');
    document.getElementsByTagName("head")[0].appendChild(fileref);
    waitForjQuery();
}

function waitForjQuery() {
    if (typeof jQuery != 'undefined') {
        // do some stuff
    } else {
        window.setTimeout(function () { waitForjQuery(); }, 100);
    }
}

Upvotes: 2

nirazul
nirazul

Reputation: 3955

My guess is that you load jQuery in the <head> section of your page. While this is not harmful, it slows down page load. Try using this pattern to speed up initial loading time of the DOM-Tree:

<!doctype html>
<html>
<head>
    <title></title>
    <meta charset="utf-8">

    <!-- CSS -->
    <link rel="stylesheet" type="text/css" href="">
</head>

<body>
    <!-- PAGE CONTENT -->

    <!-- JS -->
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
    <script>
        $(function() {
            $('body').append('<p>I can happily use jQuery</p>');
        });
    </script>
</body>

</html>

Just add your scripts at the end of your <body>tag.

There are some scripts that need to be in the head due to practical reasons, the most prominent library being Modernizr

Upvotes: 1

Gurminder Singh
Gurminder Singh

Reputation: 1755

Include your scripts at the bottom of the page before closing body tag.

More info HERE.

Upvotes: 0

Andy Zee
Andy Zee

Reputation: 335

It is advised to load your scripts at the bottom of your <body> block to speed up the page load, like this:

<body>
<!-- your content -->
<!-- your scripts -->
<script src=".."></script>
</body>
</html>

Upvotes: 4

Nishu Tayal
Nishu Tayal

Reputation: 20880

You can either use .onload function. It runs a function when the page is fully loaded including graphics.

window.onload=function(){
      // Run code
    };

Or another way is : Include scripts at the bottom of your page.

Upvotes: 4

tikider
tikider

Reputation: 550

if you can load jQuery from your own server, then you can append this to your jQuery file:

jQuery(document).trigger('jquery.loaded');

then you can bind to that triggered event.

Upvotes: 0

Related Questions