Loading jQuery plugins from third-party scripts

Introduction

In a previous article, I’ve introduced a way to build a web widget using
jQuery. One of the questions that several people asked
is how to load jQuery plugins from a third-party widget. I recently had the
need for this myself and I came up with a simple solution that I’m going to
show in this article. Note that if your plugins support AMD and you’re willing
to include a few extra kilobytes, you may consider using a tool like RequireJS. Here I’ll show you a simple do-it-yourself approach.

The problem

Quite understandably, jQuery plugins require jQuery to be present on a page in
order to load properly. This is fine under normal circumstances, but when
creating a third-party widget, we cannot expect jQuery to be loaded on the host
page. In fact even if it is loaded, we probably won’t use it but instead load
our own version of jQuery that we fully control.

To illustrate the problem we’ll create a minimal widget that just inserts
Hello, World! on the host page.

When we load the demo page in our browser, we don’t see
the expected green text. Having a look at our development console shows that
there’s a problem with the jQuery variable and that the plugin is not
available. For instance Firefox Developer Tools print these messages:

TypeError: $ is undefined
TypeError: $(...).html(...).greenify is not a function

Since the jQuery variable is not present on the page, the plugin code fails to execute and its functionality is unavailable.

The solution

The solution is to wrap the plugin code within a function definition. Once the plugin has loaded, we call that function from our code, passing it the jQuery object as its only argument. Here is the modified plugin code:

Conclusion

The technique I’ve presented in this article is a hack, but so far I’ve found that it works fine. I’ve used it
successfully with Magnific Popup,
carouFredSel, TouchSwipe and even
jQuery UI. Of course it’s not ideal that we have to modify the plugin source code, but this modification can be automated using your favourite build tool.

If you want to dig deeper into the topic, I highly recommend the book Third-Party JavaScript. I found it to be a very pleasant and informative read.