ykh
ykh

Reputation: 1815

Use Jquery inside JS file?

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

Upvotes: 0

Views: 585

Answers (4)

user659025
user659025

Reputation:

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.

Upvotes: 3

Bas Slagter
Bas Slagter

Reputation: 9929

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.

Upvotes: 0

chrisfrancis27
chrisfrancis27

Reputation: 4536

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?

Upvotes: 0

Trevor
Trevor

Reputation: 6689

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>

Upvotes: 3

Related Questions