jQuery:按顺序加载脚本

前端之家收集整理的这篇文章主要介绍了jQuery:按顺序加载脚本前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试使用jQuery动态加载一些脚本:
  1. var scripts = ['script1.js','script2.js','script3.js'];
  2.  
  3. $.each(scripts,function(i,val) {
  4. $.getScript(val,function() {
  5. console.log('loaded '+ val);
  6. });

但有时,加载脚本的顺序会更改.上一个成功加载后,如何加载每个脚本?

解决方法

通过使用$.getScript()的回调函数作为递归函数调用,可以在上一次加载完成后加载.
  1. //setup array of scripts and an index to keep track of where we are in the process
  2. var scripts = ['script1.js','script3.js'],index = 0;
  3.  
  4. //setup a function that loads a single script
  5. function load_script() {
  6.  
  7. //make sure the current index is still a part of the array
  8. if (index < scripts.length) {
  9.  
  10. //get the script at the current index
  11. $.getScript(scripts[index],function () {
  12.  
  13. //once the script is loaded,increase the index and attempt to load the next script
  14. console.log('Loaded: ' + scripts[index]);
  15. index++;
  16. load_script();
  17. });
  18. }
  19. }

您的代码中发生的是脚本在同一时间被请求,并且由于它们异步加载,它们以随机顺序返回并执行.

更新

我没有测试过,但是如果脚本在本地托管,那么您可以尝试以纯文本方式检索它们,然后将所有代码存储在变量中,直到它们全部加载为止,才能按顺序评估脚本:

  1. var scripts = ['script1.js',//setup object to store results of AJAX requests
  2. responses = {};
  3.  
  4. //create function that evaluates each response in order
  5. function eval_scripts() {
  6. for (var i = 0,len = scripts.length; i < len; i++) {
  7. eval(responses[scripts[i]]);
  8. }
  9. }
  10.  
  11. $.each(scripts,function (index,value) {
  12. $.ajax({
  13. url : scripts[index],//force the dataType to be `text` rather than `script`
  14. dataType : 'text',success : function (textScript) {
  15.  
  16. //add the response to the `responses` object
  17. responses[value] = textScript;
  18.  
  19. //check if the `responses` object has the same length as the `scripts` array,//if so then evaluate the scripts
  20. if (responses.length === scripts.length) { eval_scripts(); }
  21. },error : function (jqXHR,textStatus,errorThrown) { /*don't forget to handle errors*/ }
  22. });
  23. });

猜你在找的jQuery相关文章