Cezar Floroiu Cezar Floroiu - 1 year ago 120
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 Source

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

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

And the same for socket.io

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download