0

Select2() is not a function The best way to know if JQuery is available?

Hey guys. I've been trying to implement select2 to my project and I get this error that jQuery(...).select2() is not a function. And what I've found is that jQuery might be loaded for a couple of times and that's why the error appears. I know that jQuery works fine since jQuery.fn.jquery returns the installed version of it. However I'm not sure if this is the case, but it seems that it's the most possible, since I'm using Bootstrap, quicksandjs and other plugins that might import the jQuery multiple times to the project.

How could I check if the jQuery is loaded the second time and how could I prevent it from loading again? Many thanks.

SmallDev
  • 23
  • 4
  • Press F12, go to the network tab, count the jQuery.js files – mplungjan Jun 07 '21 at 10:42
  • A quick fix is to move the script for select2 to be last, that way it'll append itself to the current jQuery object. However bootstrap and others shouldn't include jQuery on their own, precisely to avoid conflicts like that. –  Jun 07 '21 at 10:47
  • Add `console.log(jquery.fn.jquery)` liberally through your code, eg just after your ` – freedomn-m Jun 07 '21 at 11:14
  • Also check browser network tab for select2.js and any errors – freedomn-m Jun 07 '21 at 11:15
  • 1
    @mplungjan it seems that only one jQuery file is uploaded. Well then...Maybe I was wrong and my problem is somewhere else (for example part of the JavaScript files are written in TypeScript). Thanks for you answer though. – SmallDev Jun 07 '21 at 11:30
  • @freedomn-m As I mentioned in my question I've already tried to log the version of the jQuery. The problem is that in this way I do not know how many times jQuery is loaded. – SmallDev Jun 07 '21 at 11:35
  • u cannot actually count the jquery.js files if there is a bundling of all js files. – Akshay G Jun 07 '21 at 12:06
  • 1
    @freedomn-m not sure how loging the version multiple times would help to find out if jQuery is loaded multiple times. Unless there would be like multiple versions of jQuery that are loaded. In that case, I suppose, your approach would help and show different versions. However if only one version of jQuery exists in the project, then the log shows the same version over and over again, which won't say much :) – SmallDev Jun 08 '21 at 09:26
  • @SmallDev good call - yes, I did mean to check for different versions. Try adding something to jquery after the first call and then seeing if it's still there after the page loads, something like: https://jsfiddle.net/1m6Ldozj/ If it's still there, then reloading jquery is not the issue. – freedomn-m Jun 08 '21 at 09:43

0 Answers0