Cezar Floroiu Cezar Floroiu - 1 month ago 19
Javascript Question

Programatically check in javascript if socket.io and jQuery were defined

I'm building a JS script that can be embedded in any web site. This script relies on jQuery and socket.io so I need a way to check if these 2 libraries (jQuery & socket.io) have been already included in the master page where the script will be embedded.

If they have been defined all's good. If not, I need to include them to be able to use them later. Any idea how this can be accomplished in pure Javascript?

Pseudocode of the JS widget:


  • is jQuery installed?
    => No: install

  • is socket.io installed?
    => No: install

  • do the magic stuff



Any tips will be highly appreciated :)

Answer

You can just check for the presence of their global variables.

if (!("jQuery" in window)) {
  var script = document.createElement("script");
  script.src = --jQuery URL--;
  document.head.appendChild(script);
}

And the same for socket.io