[javascript] 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
}

This question is related to javascript jquery html

The answer is


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


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.


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>

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.


Try this:

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

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.


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.


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);
    }
}

You can also use:

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

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

More info HERE.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment