How to add jQuery in JS file

541,327

Solution 1

var script = document.createElement('script');
script.src = 'https://code.jquery.com/jquery-3.4.1.min.js';
script.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script);

Solution 2

If you want to include jQuery code from another JS file, this should do the trick:

I had the following in my HTML file:

<script src="jquery-1.6.1.js"></script>
<script src="my_jquery.js"></script>

I created a separate my_jquery.js file with the following:

$(document).ready(function() {
  $('a').click(function(event) {
    event.preventDefault();
    $(this).hide("slow");
  });
});

Solution 3

You can use the below code to achieve loading jQuery in your JS file. I have also added a jQuery JSFiddle that is working and it's using a self-invoking function.

// Anonymous "self-invoking" function
(function() {
    var startingTime = new Date().getTime();
    // Load the script
    var script = document.createElement("SCRIPT");
    script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js';
    script.type = 'text/javascript';
    document.getElementsByTagName("head")[0].appendChild(script);
    // Poll for jQuery to come into existance
    var checkReady = function(callback) {
        if (window.jQuery) {
            callback(jQuery);
        }
        else {
            window.setTimeout(function() { checkReady(callback); }, 20);
        }
    };
    // Start polling...
    checkReady(function($) {
        $(function() {
            var endingTime = new Date().getTime();
            var tookTime = endingTime - startingTime;
            window.alert("jQuery is loaded, after " + tookTime + " milliseconds!");
        });
    });
})();

Other Option : - You can also try Require.JS which is a JS module loader.

Solution 4

/* Adding the script tag to the head as suggested before */
    var head = document.getElementsByTagName('head')[0];
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = "http://code.jquery.com/jquery-2.2.1.min.js";
    // Then bind the event to the callback function.
    // There are several events for cross browser compatibility.
    script.onreadystatechange = handler;
    script.onload = handler;
    // Fire the loading
    head.appendChild(script);
    function handler(){
       console.log('jquery added :)');
    }

Solution 5

In if you want to add reference to any js file, say, from your project, you may also add it directly using reference tag, in Visual Studio IDE this is handled automatically by dragging and dropping the external file from solution explorer to current file (This works for mark up files, .js & .css files too)

/// <reference path="jquery-2.0.3.js" />
Share:
541,327

Related videos on Youtube

Admin
Author by

Admin

Updated on July 08, 2022

Comments

  • Admin
    Admin 4 months

    I have some code specific to sorting tables. Since the code is common in most pages I want to make a JS file which will have the code and all the pages using it can reference it from there.

    Problem is: How do I add jQuery, and table sorter plugin into that .js file?

    I tried something like this:

    document.writeln('<script src="/javascripts/jquery.js" type="text/javascript"></script>');
    document.writeln('<script type="text/javascript" src="/javascripts/jquery.tablesorter.js"></script>');
    

    but this seems to not work.

    What is the best way to do this?

    • gblazex
      gblazex
      merge tablesorter and your code. and use server side logic to include when you need it.
  • Admin
    Admin over 13 years
    I am talking about JS files. how to add jQuery reference to a JS file
  • Salty
    Salty over 13 years
    Yes they can, Canavar. AS far as the browser is concerned, it doesn't matter whether you're adding script tags in the HTML or in a script itself, because it interprets the result the same.
  • Timothy Groote
    Timothy Groote over 11 years
    So what, it's still a good answer, and it might help someone else looking for how to do it. Welcome to stackoverflow, R-The_Master!
  • Lri
    Lri about 11 years
    @genesis φ This is currently the top Google result for jquery include js and has 13k views lol.
  • zeboidlund
    zeboidlund almost 11 years
    Damn straight! certainly helped me out :P. Awesome!
  • tushar747
    tushar747 over 10 years
    Helped me out... 3 years later :)
  • KevinO
    KevinO about 10 years
    I just want to point out: The order that you include your js files is important.
  • RozzA
    RozzA almost 9 years
    this solution does nothing, as the script tag was already being seen as a string, not as markup.
  • Rahul Patwa
    Rahul Patwa over 8 years
    worked for me too.. so simple and straight forward :)
  • Mark Rotteveel
    Mark Rotteveel over 2 years
    Please don't post only code as answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes.
  • Nishant Bhagat
    Nishant Bhagat about 1 year
    Thanks man....That's the answer I needed. Just change the http to https and it works perfectly.