关于 jQuery getScript() 的问题
$.getScript("somescript.js", function() {
alert('Load Complete');
});
- 加载后,是否会缓存,或者如果多次引用,是否会再次加载?
- 如果某个事件依赖于正在加载的此文件,那么在文件加载时间较长或未加载的情况下,该事件是否会延迟失败/超时?
- 如果文件由于某种原因无法加载,我该如何检查并执行某些操作?
预先感谢您的帮助。
$.getScript("somescript.js", function() {
alert('Load Complete');
});
- Once loaded, is it cached or is it loaded again if referenced more than once?
- If an event depends on this file being loaded, will the event be delayed of fail/timeout in case the file takes longer to load or doesn't load?
- How do I check and do something in case the file fails to load for some reason?
Thanks in advance for your help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
1) 通过 AJAX 对脚本的 jQuery 请求永远不会被缓存,除非您在 $.ajax() 函数中将其指定为选项。来自文档:
“缓存,布尔值
默认: true,对于 dataType 'script' 和 'jsonp' 为 false
如果设置为 false,将强制浏览器不缓存您请求的页面。"
2)< /strong> 我想我需要查看示例代码来掌握问题的这一部分。
3) 如果 $.getScript() 失败,您将无法执行任何操作。但是,你应该知道 $.getScript() 只是 $.ajax() 的简写版本,相当于:
这意味着你可以实现
error
回调,做一些聪明的事情如果文件加载失败,即:1) jQuery requests for scripts via AJAX are never cached unless you specify that as an option in the $.ajax() function. From the documentation:
"cache, Boolean
Default: true, false for dataType 'script' and 'jsonp'
If set to false it will force the pages that you request to not be cached by the browser."
2) I think I need to see sample code to grasp this part of the question.
3) You can't do anything if $.getScript() fails. But, you should be aware that $.getScript() is just a short-hand version of $.ajax(), equivilant to:
This means that you can implement the
error
callback, to do something clever if the file fails to load, ie:除了 Glen 的回答之外,我还想提供另一个选项:
Supported on jQuery 1.12.0+
In addition to Glen's answer I would like to offer another option:
Supported on jQuery 1.12.0+