【发布时间】:2013-12-06 21:53:46
【问题描述】:
这是用于在网页上加载 Disqus cmets 的(默认/官方)JavaScript 代码:
(代码 #1)
<script type="text/javascript">
var disqus_shortname = 'paulund';
(function() {
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
</script>
在我看来,代码异步执行 HTTP 请求;但这不是重点。
问题是,我需要对代码进行一些更改,以便仅当用户向下滚动到 cmets 部分时才加载 cmets,例如延迟加载。 我有两种工作方法可以做到这一点。
(代码 #2)
jQuery(document).ready(function($){
$('#comments').waypoint(function () {
var disqus_shortname = 'paulund';
$(function() {
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
}, { offset: '100%', triggerOnce: true });
});
(代码 #3)
jQuery(document).ready(function($){
$('#comments').waypoint(function () {
var disqus_shortname = 'paulund';
$.ajax({
type: "GET",
url: "http://" + disqus_shortname + ".disqus.com/embed.js",
dataType: "script",
cache: true
});
}, { offset: '100%', triggerOnce: true });
});
问题:
除了我现在用 jQuery 做这件事的明显事实之外,代码 #1 和 #2 和 #2 之间有什么区别吗? strong>#1 和 #3,是吗?我可能做错了什么,我完全错过了?
为什么代码 #2 和 #3 在以
$.noConflict();开头时不起作用? (After all I found it in the docs as well.)
例如,这不会做任何事情。 (但在浏览器控制台中出现错误,“Uncaught TypeError: Cannot call method 'noConflict' of undefined.”。)
$.noConflict();
jQuery(document).ready(function($){
$('#comments').waypoint(function () {
var disqus_shortname = 'paulund';
$.ajax({
type: "GET",
url: "http://" + disqus_shortname + ".disqus.com/embed.js",
dataType: "script",
cache: true
});
}, { offset: '100%', triggerOnce: true });
});
【问题讨论】:
-
不,没有区别。我会使用方法 3,甚至可能缩短为 $.getScript。
-
@KevinB 如果可能,请回答。另外,我不知何故碰巧错过了早些时候的一个问题。请查看更新后的问题。
-
顺便说一句,您的 #2 不需要
$({...})()包装脚本元素创建代码 - 在任何情况下它都不应该有$因为您不需要页面加载后准备好文档处理程序,但是当整个内容包含在另一个函数中时,您也不需要 #1 版本中的匿名函数。 (#1 中立即调用的匿名函数大概是为了将dsq变量保持在全局范围之外。) -
@nnnnnn 所以,你建议我这样做:pastebin.com/8LUiHLf5 或这样:pastebin.com/6Uq3yKJG。对吗?
-
如果你想使用#2,那么是的,我建议的是第一个 pastebin 样本。如果您想使用 jQuery,那么我认为使用 #3 或您的第二个 pastebin 示例更有意义。
标签: javascript jquery ajax asynchronous jquery-waypoints