0

I have created an external JS file, this JS file contains some methodes that uses JQuery, i can't seem to find a way to refernece the JQuery file on JS file and user it there. Any help would be appreciated

ykh
  • 1,775
  • 3
  • 31
  • 57

4 Answers4

3

In your HTML file, include the jQuery file first and then your file:

<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="myfile.js"></script>
Trevor
  • 6,659
  • 5
  • 35
  • 68
3

Two things are important to reach your goal:

  1. Include the javascript files. Include both files in your HTML via a script-tag, starting with jQuery to make sure it is loaded when used by your javascript.
  2. Ensure jQuery. This is something way to less people tell you. If you write JS and jQuery for a long time, sooner or later you'll encounter a case where something is overwriting the $-variable. The $-variable is used by jQuery and everyone coding with it because of the obvious fact that it's just one char. However, jQuery doesn't have any "rights" or something for the $-variable, so basically anything or anyone could overwrite it. So I recommend your own javascript file looks like this:

    (function($) { // your coding starts here. })(jQuery);

You probably already encountered this when dissecting jQuery plugins from people who know what they're doing. It creates an anonymous function that takes one parameter which will be know by $ inside the function. The function is then immediately called and hands over the jQuery function. This way you can be sure that, whatever happens outside this function, inside of it $ stands for jQuery.

0

As long as you include the jQuery core in your HTML, the global jQuery object is available in any of your scripts. Is there a specific problem you're having?

chrisfrancis27
  • 4,516
  • 1
  • 24
  • 32
  • I tried, i added the JQuery in the HTML but it seems to be not working inside the JS File – ykh Sep 20 '12 at 14:29
  • If you want to dynamically add the jQuery script from your JS file, rather than including it in the HTML, you need to create a ` – chrisfrancis27 Sep 20 '12 at 14:31
0

You must write a piece of script (plain JS) that checks for the presence of jQuery, if not, it must append a script reference to the page pointing to a jQuery file (or Google CDN) to include jQuery. After that, you can use jQuery in the rest of your script.

I think it will involve some interval that checks wheter the jQuery object is present or not and waits with executing the rest of your code till that it the case.

Google for this, I'm sure there is something out there.

Bas Slagter
  • 9,831
  • 7
  • 47
  • 78