To make a regular JS function accessible everywhere I just need to declare it outside jQuery(document).ready(function($){})
. But what if this JS function contains jQuery stuff? How then can I make it accessible from anywhere, particularly from different JS files?
Asked
Active
Viewed 244 times
-1

Niki van Stein
- 10,564
- 3
- 29
- 62

drake035
- 3,955
- 41
- 119
- 229
-
You load jQuery in your header. This makes jquery accessible anywhere. Loading multiple scripts into a page is like injecting code. Define a function in one, in the proper order, and the second script can access it. – Sterling Archer Dec 02 '15 at 15:22
-
You have to imagine that all javascript gets run in the order in which they're loaded into the page, so if jQuery is included, any script afterwards can potentially use it (that doesn't necessarily mean it *should* or that it would benefit from that). – Neil Dec 02 '15 at 15:23
-
See also [this question](http://stackoverflow.com/questions/3809862/can-we-call-the-function-written-in-one-javascript-in-another-js-file) – Draco18s no longer trusts SE Dec 02 '15 at 15:25
1 Answers
1
In exactly the same way. As long as you included jQuery
before your function.
So
<script src="jquery.js"></script>
<script src="yourglobalfunctionshere.js"></script>
<script src="documentreadystuff.js"></script>
<script>
jQuery(document).ready(function($){
//or here some stuff
})
</script>

Niki van Stein
- 10,564
- 3
- 29
- 62
-
Doesn't that need to be an IIFE if you're injecting `$` into it? – Sterling Archer Dec 02 '15 at 15:24
-
1@SterlingArcher No, this is shorthand for document ready handler passing explecitely '$' as jQuery reference inside ready handler. The first parameter of `ready` pseudo event handler is always `jQuery`: `However, the handler passed to the .ready() method can take an argument, which is passed the global jQuery object. This means we can rename the object within the context of our .ready() handler without affecting other code` – A. Wolff Dec 02 '15 at 15:26