Assuming the code you've shown is at global scope, I can only think of three possibilities:
You've included Sliders.js
before including jQuery and the code you've shown in the question.
You're using an iframe
and loading Slider.js
into it, but jQuery isn't loaded in that iframe
; your code is in the main document (or a different iframe
) where jQuery is loaded, so it has $
but the iframe
with Slider.js
doesn't. Remember an iframe
is a completely different window from the window containing it. If you want to use jQuery in that iframe
, you have to load it in that iframe
.
(This seems unlikely) Code running after your code is doing this:
$.noConflict(); // This part is optional but likely to be there
delete $; // This causes the specific error you're seeing
#1 is the most likely scenario, followed by #2; #3 is possible but unlikely.
I won't do an example of #2 because it's awkward with Stack Snippets, but here's an example of #1:
<script><!-- This is Slider.js -->
$(document).on("click", ".slider", function() {
// ...
});
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(() => {
console.log("ready");
});
</script>
And here's an example of #3:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(() => {
console.log("ready1");
});
</script>
<script>
$.noConflict(); // This is optional but likely to be there
delete $; // This causes the specific error you're seeing
</script>
<script>
$(document).ready(() => {
console.log("ready2");
});
</script>
Notice we see ready1
but get an error instead of seeing ready2
.
If the code following your code only did $.noConflict()
, you'd still get an error, but it would be a different one ("$
is not a function). So something is actually removing the $
property from the window object (via delete $
or similar).
Side note: $(document).ready(someFunction)
has been deprecated for some time now, details here. Use $(someFunction)
instead if you really need to ask jQuery to wait for the DOMContentLoaded
event, or better yet use modules (they won't be run until the main parsing of the HTML is completely), or defer
on your script
tag, or put your script
tag at the very end of the document. (But there are times you don't control the script
tag, and in those situations $(someFunction)
can be useful.)