开发者

Dynamically loading jQuery library from a custom component and ensuring only one instance

Say I have a web component that uses jQuery and I want to distribute it as a packaged component.

I need a way to ensure that the jQuery library is available on or after the page loads, but I also want to check that the containing html page, or another unknown component that may reference jQuery hasn't already added the library to the page.

At the moment the best开发者_StackOverflow社区 example I've seen is this

http://www.squidoo.com/load-jQuery-dynamically

It would need a little tweaking, but I was wondering if there were any other best practices.


You can use two approaches to solve this.

  1. Just use jQuery's noConflict() mode this way you can always load your jQuery and the worst that could happen is that jQuery gets loaded twice but as you use noConflict() mode no problems will arise because of that.

  2. Or you simply check like this

Code to check

if (typeof($) !== "undefined" && typeof($.fn) !== "undefined" && typeof($.fn.jquery) !== "undefined")
  // don't do anything jQuery already loaded
  // or check if the version included is "new" enough
  // hint: $.fn.jquery --> version number of jQuery
  // if jQuery too old load your version with noConflict mode
else
  //load your jQuery (e.g. insert programmatically a `script` tag)


I like Jitter's answer, and my answer is that you can always tell people that they have to load jQuery before yours or yours won't work. That's what a LOT of people do.

You don't always have to hold their hands for them. Sometimes you CAN set a requirement. I've done several little packaged items that required jQuery and nobody raised an eyebrow at me.

But I like Jitter's answer. Just run an ifnotdef and load it yourself. Works easily and simply.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜