views:

716

answers:

3

Hello,

I have written a jQuery plugin, but I want it to check if jQuery has been loaded, if not then load it, as well as a couple of other javascript files and also check if CSS file has been loaded, if not then load it.

Am wondering how to go about it?

thank you very much for your time.

A: 

The following should work. It may not be entirely optimized, though.

if (typeof jQuery == "undefined") {
    var js = document.createElement("script");
    js.setAttribute("src",...path to jquery...);
    js.setAttribute("type","text/javascript");
    document.head.appendChild(js);
    //ditto for other files you mentioned 
}

function isCSSLoaded(uri) {
    var links = document.getElementsByTagName("link");
    for (var i =0, len = links.length; i<len;++i) {
        if (links[i].getAttribute("src") === uri) return true;
    }
    return false;
}

if (isCSSLoaded(...pathToYourCSSFile...) {
    var css = document.createElement("link");
    css.setAttribute("href",...path to css file...);
    css.setAttribute("media","screen");
    css.setAttribute("rel","stylesheet");
    css.setAttribute("type","text/css");
    document.head.appendChild(css);
    //ditto for other files you mentioned 
}

EDIT: note the above only applies to CSS loaded via links, and not those using @import

Jonathan Fingland
Your isCSSLoaded loaded function does not check whether or not the CSS has been loaded, only that a <link> tag is present with a specified src. If I create a link tag progmatically and put it in the document with the src, X, and use your function right away it will falsely say that the CSS is loaded.
Eli Grey
A: 

Your plugin, unless it is comparable to jQuery in size and complexity, should probably not be loading jQuery. I think simply checking if jQuery is present, and throwing a warning if it is absent is sufficient for any developers to understand what is happening.

I suppose you could be working on a plugin that people will often include without 'knowing' if they have jQuery or not.

Justin Meyer
+2  A: 

To detect if CSS is loaded

Add this to your CSS:

._css_loaded_test {
  display: none;
}

Define this JavaScript function:

function cssIsLoaded() {
  var test = document.createElement("div");
  test.className = "_css_loaded_test";
  return getComputedStyle(test, null).display === "none";
}

To detect if jQuery is loaded

Use this JavaScript to detect if jQuery is loaded:

if (typeof jQuery !== "undefined") {
  // put your code here
}
Eli Grey