Best way to package a JavaScript library that requires jQuery?

I am writing a very basic JavaScript library that uses the $.ajax() function of jQuery.

How should I manage this dependency? Should I instruct users of my library to include jQuery themselves? Should I use something like RequireJS or script tag insertion to load jQuery within the library? If the latter would be better, how do I do this without causing a conflict if the user is already using jQuery?


I think it kinda depends if you have more dependencies, other than jQuery.

If jQuery is your only dependency, and your library doesn't really need it's own module dependency system, I wouldn't recommend RequireJS. Just check for the existence of jQuery in your library, and throw an error otherwise.

If you're however looking to make an flexible and maintainable libary, I would recommand using some module loader (like RequireJS). This also gives you the advantage of using a build system which allows you to combine and pack your library


I ended up writing my own function to fetch JSON data as silly little me recommended in the original post. Thanks to everyone who replied. The guidance on JavaScript library dependencies was very valuable, even though I went down this other route.

I used this Stack Overflow answer as a guide for writing my own function to fetch JSON. I needed to fetch the data synchronously, so I adjusted the function with the tips outlined in this other article.

In the end, my function looked like this. I hope it helps someone else who comes along.

var fetchJSON = function(path, callback) {
  var httpRequest = new XMLHttpRequest();
  httpRequest.open('GET', path, false);
  httpRequest.send();
  if (httpRequest.readyState === 4) {
    if (httpRequest.status === 200) {
      var data = JSON.parse(httpRequest.responseText);
      if (callback) callback(data);
    }
  }
}

I would recommend you to advice the users to include jquery first. If you let me choose any example, you will see that this is a really used approach (eg .net framework)

链接地址: http://www.djcxy.com/p/12900.html

上一篇: 在页面之间来回发送PHP变量

下一篇: 打包需要jQuery的JavaScript库的最佳方法是什么?