2011-01-18 118 views
1

我想作这样的事情(类似于):如何在JavaScript中实现`使用`?

using("content/jquery.js"); 

$("div").fadeOut(); 

所以,如果content/jquery.js是不是在head我想加载它,它加载后继续执行的script

是否有可能实现这个或类似的东西?注意:我可以有多于1个using

回答

4

这些被称为脚本加载器。

你可以看看RequireJS,其行为在一个非常相似的方式:

require(["helper/util"], function() { 
    //This function is called when scripts/helper/util.js is loaded. 
}); 

还有LabJSControlJS,这是更侧重于异步脚本加载,而不是依赖关系,但可能是值得一试出。同样在这个类别中,我们拥有@ jAndy的SupplyJS

+0

不要忘记supplyJS:O)https://github.com/jAndreas/Supply – jAndy 2011-01-18 23:12:28

1

如果你知道你将调用的时间提前函数的名称,你可以使用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. 
    } 
} 

是我能想到的两种方法我的头顶。

2

您可以使用getScript

$.getScript('test.js', function() { 
    alert('Load was performed.'); 
}); 
+0

+1很好的答案,我忘了。这很有趣,因为在这个例子中,OP正在尝试加载jQuery,而使用jQuery。但是你必须有一些脚本来启动它,这取决于你的需求。 – 2011-01-18 23:20:29