我有一个 javascript 文件,用户可以将其嵌入到他们的网站上。它使用 coffeescript 和 Rails 资产管道将一堆文件编译成一个。
# 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')
这可以使用示例页面按预期工作:
<!DOCTYPE html>
<head></head>
<body>
<script src="http://localhost:3000/assets/test.js" type="text/javascript"></script>
</body>
</html>
但是这个脚本是一个小部件,所以它应该可以嵌入到任何网站上。如果用户在它下面添加自己的 jquery,那么事情就会中断:
<!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>
这给出了错误Uncaught TypeError: Object function (a,b){return new e.fn.init(a,b,h)} has no method 'cookie'
将所有内容都包含在 test.js 中以便自包含的最佳方法是什么?我认为将所有内容包装在匿名函数中的咖啡脚本在这里可能会有所帮助,但我想不会。
谢谢!