jquery.getScript在本地工作,但在github页面上工作



我正在与jekyll建立一个网站。许多人会在主页上随机显示的不同JavaScript草图做出贡献:其中一些将使用p5.js编写,其他则与其他库一起编写。

由于我不想加载页面加载的所有库,所以每个脚本都会生成一个带有一个对象的JSON:

[
   {
      "title":"Title to display",
      "author":"Author",
      "description":"javascript, Processing",
      "kind":"javascript",
      "href":"link to the js hosted on GitHub Pages",
      "includes":[
         "link to external library hosted on CDN",
         "link to external library hosted on CDN"
      ]
   }
]

然后,使用jQuery,我正在使用此脚本加载所有内容:

var loadedData;
$(function() {
    // Load all the scripts in an array
    $.getJSON("{{ site.url }}/homepage.json", function(data) {
      loadedData = data;
      randomPost();
    });
    $("#jsRefresh").click(function() {
      $("canvas").remove();
      randomPost();
    });
});
function randomPost() {
  $("#loading").show();
  item = loadedData[Math.floor(Math.random() * loadedData.length)];
  var defer = $.Deferred();
  $.each(item.includes, function(index, value){
    defer.then(function() {
      $.getScript(value)
    });
  });
  defer.then(function() {
    $.getScript(item.href)
  });
  defer.resolve();
  $.when(defer).done(function() {
    $("#loading").hide();
    $(".item-title").html(item.title + ' | ' + item.author);
    $(".item-description").html(item.description);
  })
}

此代码在我的本地服务器上工作,但是当我在github页面上上传时,它在页面加载上无法正确加载。

如果我单击触发 randompost()的刷新链接,它将加载上一个脚本。

现场示例当前托管在这里

您的整个$。当时仅使用一个诺言,然后立即解决它,而不是基于任何getcript完成。由于您立即解决它,因此几乎完全不使用任何承诺。

还请注意,$.getScript$.ajax快捷方式,$.ajax本身返回Promise

这样的规范将是做出一系列承诺,而$.when直到诺言的数组全部解析

才能解决

类似:

 // library script promises
 var requests = item.includes.map(function(value) {
   return $.getScript(value)
 });
 // `$.when` doesn't accept array in jQuery versions <3
 $.when.apply(null, requests).then(function() {
   //want this to only load after include requests have loaded
   var mainScriptPromise =  $.getScript(item.href);           
    // return it to the next then() 
    return mainScriptPromise;
 }).then(function() {
   // fires after the main script promise resolves
   $("#loading").hide();
   $(".item-title").html(item.title + ' | ' + item.author);
   $(".item-description").html(item.description);
 });

请注意,如果任何承诺无法解决

,您还需要添加自己的错误处理

使用$.get

演示

注意,您可能需要考虑使用诸如require.js

之类的负载管理器

最新更新