我正在尝试使用jQuery动态加载一些脚本:
- var scripts = ['script1.js','script2.js','script3.js'];
- $.each(scripts,function(i,val) {
- $.getScript(val,function() {
- console.log('loaded '+ val);
- });
但有时,加载脚本的顺序会更改.上一个成功加载后,如何加载每个脚本?
解决方法
通过使用$.getScript()的回调函数作为递归函数调用,可以在上一次加载完成后加载.
- //setup array of scripts and an index to keep track of where we are in the process
- var scripts = ['script1.js','script3.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(scripts[index],function () {
- //once the script is loaded,increase the index and attempt to load the next script
- console.log('Loaded: ' + scripts[index]);
- index++;
- load_script();
- });
- }
- }
您的代码中发生的是脚本在同一时间被请求,并且由于它们异步加载,它们以随机顺序返回并执行.
更新
我没有测试过,但是如果脚本在本地托管,那么您可以尝试以纯文本方式检索它们,然后将所有代码存储在变量中,直到它们全部加载为止,才能按顺序评估脚本:
- var scripts = ['script1.js',//setup object to store results of AJAX requests
- responses = {};
- //create function that evaluates each response in order
- function eval_scripts() {
- for (var i = 0,len = scripts.length; i < len; i++) {
- eval(responses[scripts[i]]);
- }
- }
- $.each(scripts,function (index,value) {
- $.ajax({
- url : scripts[index],//force the dataType to be `text` rather than `script`
- dataType : 'text',success : function (textScript) {
- //add the response to the `responses` object
- responses[value] = textScript;
- //check if the `responses` object has the same length as the `scripts` array,//if so then evaluate the scripts
- if (responses.length === scripts.length) { eval_scripts(); }
- },error : function (jqXHR,textStatus,errorThrown) { /*don't forget to handle errors*/ }
- });
- });