小书签等待 Javascript 加载
我有一个加载 jQuery 和其他一些 js 库的书签。
我该如何:
- 等到我正在使用的 javascript 库可用/加载。 如果我尝试在脚本完成加载之前使用该脚本,例如在加载之前将 $ 函数与 jQuery 一起使用,则会引发未定义的异常。
- 确保我加载的小书签不会被缓存(不使用服务器标头,或者显然,这是一个 javascript 文件:元标记)
有人知道动态添加的 javascript 的 onload 是否可以在IE? (与此帖子相矛盾)
解决这些问题的最简单的解决方案是什么?
I've got a bookmarklet which loads jQuery and some other js libraries.
How do I:
- Wait until the javascript library I'm using is available/loaded. If I try to use the script before it has finished loading, like using the $ function with jQuery before it's loaded, an undefined exception is thrown.
- Insure that the bookmarklet I load won't be cached (without using a server header, or obviously, being that this is a javascript file: a metatag)
Is anyone aware if onload for dynamically added javascript works in IE? (to contradict this post)
What's the simplest solution, cleanest resolution to these issues?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这取决于您实际加载 jQuery 的方式。 如果要将脚本元素附加到页面,则可以使用与 jQuery 动态加载脚本相同的技术。
编辑:我做了功课,实际上从 jQuery 代码中提取了一个 loadScript 函数以在您的书签中使用。 它实际上可能对许多人(包括我)有用。
It depends on how you are actually loading jQuery. If you are appending a script element to the page, you can use the same technique that jQuery uses to dynamically load a script.
EDIT: I did my homework and actually extracted a loadScript function from the jQuery code to use in your bookmarklet. It might actually be useful to many (including me).
回答你的第一个问题:Javascript 是按顺序解释的,因此在加载库之前,任何后续的小书签代码都不会执行(假设库被成功解释 - 没有语法错误)。
为了防止文件被缓存,您可以附加一个无意义的查询字符串...
To answer your first question: Javascript is interpreted sequentially, so any following bookmarklet code will not execute until the library is loaded (assuming the library was interpreted successfully - no syntax errors).
To prevent the files from being cached, you can append a meaningless query string...
我注意到,在 Chrome 中,使用 @Vincent Robert 的技术时,加载脚本的顺序是不确定的。 在这种情况下,进行一些修改会有所帮助:
I've paid an attention that in Chrome the order of scripts that are loaded is undetermined, when using @Vincent Robert's technique. In this case a little modification helps:
我对这个有了一些了解,但并不完全。 如果有一个独立的小书签示例来演示如何避免缓存,那就太好了。
I got a little closer with this, but not completely. It would be nice to have a discrete, example of a bookmarklet that demonstrated how to avoided caching.