I have a javascript file that users can embed on their site. It uses coffeescript and the Rails asset pipeline to compile a bunch of files into one.
# The following dependencies will be compiled into test.js (rails asset pipeline manifest file)
#
#= require jquery
#= require jquery.cookie
jQuery ->
$.cookie('foo', 'bar')
console.log $.cookie('foo')
This works as expected with a sample page:
<!DOCTYPE html>
<head></head>
<body>
<script src="http://localhost:3000/assets/test.js" type="text/javascript"></script>
</body>
</html>
But this script is a widget so it should be embeddable on any site. If the user adds their own jquery below it, then things break:
<!DOCTYPE html>
<head></head>
<body>
<script src="http://localhost:3000/assets/test.js" type="text/javascript"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</body>
</html>
This gives the error Uncaught TypeError: Object function (a,b){return new e.fn.init(a,b,h)} has no method 'cookie'
What is the best way to wrap up everything in test.js so is self contained? I thought coffeescript wrapping everything in an anonymous function might help here but I guess not.
Thanks!
This tutorial provides some clues: http://alexmarandon.com/articles/web_widget_jquery/
It sounds like I might have to include the minified source code for plugins (like jquery.cookie) in the anonymous function. The assets pipeline doesn’t allow you do require statements like that unless they are at the top of the file (in the first comment block): https://github.com/sstephenson/sprockets/issues/398