好的,所以我让自己成为了一个小对象,使用 JSON 来评估整个加载 jquery 与一个备用的东西(并使用它来加载我所有的 js 文件,事实上):
<script type="text/javascript">
/* Library loading object */
var ScriptLoader = {
//values
head_tag : document.getElementsByTagName('head')[0],
fallback : false,
//functions
createScript: function(script_path) {
var script_tag = document.createElement('script');
script_tag.type = 'text/javascript';
script_tag.src = script_path;
return script_tag;
},
addToHead : function(tag) {
ScriptLoader.head_tag.appendChild(tag);
},
addLoadEvent : function(func) {
var prev = window.onload;
if (typeof window.onload !== 'function') {
window.onload = func;
} else {
window.onload = function() {
prev();
func();
}
}
}
};
//Loading jquery, modernizr, and my js files when window is ready.
ScriptLoader.addLoadEvent(function() {
/* Load from jquery's cdn for speed + auto latest download */
var scripts = ['http://code.jquery.com/jquery-latest.min.js',
'scripts/modernizr.js',
'scripts/script.js'],
idx = 0;
for (; idx < scripts.length; idx++) {
ScriptLoader.addToHead(ScriptLoader.createScript(scripts[idx]));
}
});
//jquery fallback
ScriptLoader.addLoadEvent(function() {
if (typeof window.jQuery === undefined) {
ScriptLoader.fallback = true;
ScriptLoader.addToHead(ScriptLoader.createScript('scripts/jquery-mini-1.6.2.js'));
}
});
//grab info
(function() {
setTimeout(function() {
console.log('jquery loaded: ' + (window.jQuery !== undefined));
console.log('used fallback: ' + ScriptLoader.fallback);
}, 1000);
})();
现在,这完全有效,但请注意不断调用我的对象名称?有没有办法简单地使用这个而不是那个?我有点得到整个功能级范围的唯一东西,并且还意识到这被分配给最近的封闭函数,但我对此并不十分清楚..
我也简要阅读了但不完全理解闭包..
谢谢 :)