如何在JavaScript中实现`使用`?
问题描述:
我想作这样的事情(类似于c#):如何在JavaScript中实现`使用`?
using("content/jquery.js");
$("div").fadeOut();
所以,如果content/jquery.js
是不是在head
我想加载它,它加载后继续执行的script
。
是否有可能实现这个或类似的东西?注意:我可以有多于1个using
答
如果你知道你将调用的时间提前函数的名称,你可以使用typeof
来检查他们的存在:
if (typeof($) == 'function') {
// Code here that uses jQuery
} else {
// Something else here that loads the script.
}
如果你不能确定你会使用什么功能您可能想要检索脚本元素的列表并检查它们。更多沿着这些线:
var scripts = document.getElementsByTagName('script');
for (var i = 0, l = scripts.length; i < l; ++i) {
if (scripts[i].src == myVal) {
// do something here
} else {
// wait for the script to load, or just leave off the else.
}
}
是我能想到的两种方法我的头顶。
答
您可以使用getScript:
$.getScript('test.js', function() {
alert('Load was performed.');
});
+0
+1很好的答案,我忘了。这很有趣,因为在这个例子中,OP正在尝试加载jQuery,而使用jQuery。但是你必须有一些脚本来启动它,这取决于你的需求。 – 2011-01-18 23:20:29
不要忘记supplyJS:O)https://github.com/jAndreas/Supply – jAndy 2011-01-18 23:12:28