以下是有效的,但我需要将它分发给可能不喜欢将所有这些脚本粘贴到其主页的客户端。只是想知道它是否可以简化?我需要加载Jquery 1.71,然后是UI,然后是我自己的脚本,然后在我自己的脚本中调用该函数。甚至最小化它相当长。
希望一些javascript大师可以提供帮助。谢谢!
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js';
script.type = 'text/javascript';
head.appendChild(script);
if (script.onreadystatechange) script.onreadystatechange = function () {
if (script.readyState == "complete" || script.readyState == "loaded") {
script.onreadystatechange = false;
//alert("complete");
load_script();
}
} else {
script.onload = function () {
//alert("complete");
load_script();
}
}
//setup array of scripts and an index to keep track of where we are in the process
var scripts = ['script/jquery-ui-1.8.7.custom.min.js', 'script/wfo171.js'],
index = 0;
//setup a function that loads a single script
function load_script() {
//make sure the current index is still a part of the array
if (index < scripts.length) {
//get the script at the current index
$.getScript('http://mydomainn.com/script/' + scripts[index], function () {
//once the script is loaded, increase the index and attempt to load the next script
//alert('Loaded: ' + scripts[index] + "," + index);
if (index != 0) {
LoadEdge();
}
index++;
load_script();
});
}
}
function LoadEdge() {
Edge('f08430fa2a');
}
答案 0 :(得分:4)
只要你有jQuery就可以使用它的力量:
$.when.apply($, $.map(scripts, $.getScript)).then(LoadEdge);
这取决于其延迟功能 - 每个URL都被延迟getScript
替换(这将获取脚本),然后将这些延迟传递给$.when
,以便您可以使用添加回调所有脚本加载完成后调用.then
。
答案 1 :(得分:1)
为什么不尝试使用onload事件来确保在尝试执行之前加载所有内容?
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="http://mydomainn.com/script/jquery-ui-1.8.7.custom.min.js"></script>
<script src="http://mydomainn.com/script/wfo171.js"></script>
<script>
$(function() { // this executes when the page is ready
Edge('f08430fa2a');
});
</script>
(检查脚本上的路径,您似乎是从/script/script
加载的,不确定这是否正确所以我将其删除了。