1

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.

3 Answers 3

2

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
}
Sign up to request clarification or add additional context in comments.

1 Comment

I don't care about ie either :) but I don't think getComputedStyle() will work on ie8 and before. Maybe use currentStyle - see: quirksmode.org/dom/w3c_css.html#t01
0

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.

Comments

-1

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

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.