23

I have a javascript file and I want to include jquery in this js file. Do you have a suggestion?

cagin
  • 5,772
  • 14
  • 74
  • 130
  • 3
    how about this http://stackoverflow.com/questions/5577771/how-to-include-jquery-js-in-another-js-file – ayush Sep 21 '11 at 08:34
  • 2
    Because, I want to use jquery library in my javascript file. Do you know another way? – cagin Sep 21 '11 at 08:35

5 Answers5

24

Simply include the JavaScript for jQuery before you include your own JavaScript:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script src="path/to/your/script.js"></script>

Though others have suggested simply copying and pasting jQuery into your own JavaScript file, it's really better to include jQuery separately from a canonical source as that will allow you to take advantage of the caching that your browser and intermediate servers have done for that file.

Michael Aaron Safyan
  • 93,612
  • 16
  • 138
  • 200
  • sadly this does not work for me, using the chain `[main webpage ->includes [work_app.php -> includes jQuery.js + another.js]]` jQuery never gets loaded in time and yes, my script is included below jquery include. – RozzA Dec 01 '13 at 21:39
  • What if loading jquery takes too long, won't the code from script.js start executing before jquery has been loaded? – Incerteza Feb 28 '15 at 14:57
  • @RozzA ,does your script tag have the "async" or "defer" attributes? If not, then the scripts should be loaded/executed in the order that they appear on the page. If they do use "async" and "defer", then you could have JavaScript listen for script events and trigger execution once the other script has completed loading/execution. – Michael Aaron Safyan Apr 10 '16 at 16:39
21
var jq = document.createElement("script");

jq.addEventListener("load", proceed); // pass my hoisted function
jq.src = "//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js";
document.querySelector("head").appendChild(jq);

function proceed () {
    // jQuery load complete, do your magic


}
neaumusic
  • 10,027
  • 9
  • 55
  • 83
5

Just merge the files.

cat jquery.js >> a_javascript_file.js

Or, since you probably want jQuery first:

cat a_javascript_file.js jquery.js > tmp.js;
mv tmp.js a_javascript_file.js
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
4

If you want to include a js file into a js file... javascript does not have something like an include function but you can load the file with an ajax request or add a script tag to the html with js. Check out the following link, a really interesting read!

How do I include a JavaScript file in another JavaScript file?

Community
  • 1
  • 1
kasper Taeymans
  • 6,950
  • 5
  • 32
  • 51
-2

I suggest you to use a line of code inside your java script library.

document.write("Script/jquery.min.js'></script>");

with the help of this, you do not need to add references of two files on your page.

DK Chauhan
  • 194
  • 1
  • 11