使用Promises使用JavaScript加载jQuery [英] Load jQuery with JavaScript using Promises

查看:61
本文介绍了使用Promises使用JavaScript加载jQuery的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

上一个问题揭示了如何使用本机JavaScript在jQuery中加载.

我已经成功地使用了答案中的回调代码,在此处进行了复制:

A previous question revealed how to load in jQuery using native JavaScript. I've successfully used the callback code from the answer there, replicated here:

// Anonymous "self-invoking" function
(function() {
    // Load the script
    var script = document.createElement("SCRIPT");
    script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js';
    script.type = 'text/javascript';
    document.getElementsByTagName("head")[0].appendChild(script);

    // Poll for jQuery to come into existance
    var checkReady = function(callback) {
        if (window.jQuery) {
            callback(jQuery);
        }
        else {
            window.setTimeout(function() { checkReady(callback); }, 100);
        }
    };

    // Start polling...
    checkReady(function($) {
        // Use $ here...
    });
})();

如何使用

How can I accomplish the same thing using native JavaScript Promises?

我问的原因是因为我突然需要链接早期的回调,这是一个令人毛骨悚然的烂摊子.我希望Promises是更好的方法,并且我对使用加载程序框架没有真正的兴趣.

The reason I ask is because I suddenly need to chain off of the earlier callback, and it's a friggin' mess. I'm hoping Promises are a better way, and I have no real interest in using a loader framework.

这是我到目前为止所拥有的,但是Promise总是最终被拒绝:

Here's what I've got so far, but the Promise always ends up rejected:

// This code doesn't work quite right.
// Poll for jQuery to come into existance using a Promise
var jQueryReady = new Promise(
    function(resolve, reject) {

      // Load jQuery
      var script = document.createElement('SCRIPT');
      script.type = 'text/javascript';
      script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js';
      document.getElementsByTagName('head')[0].appendChild(script);

      if (window.jQuery) {
        resolve("YAY");
      } else {
        reject("UGH");
      }
    });

jQueryReady.then(
  function(success) {
    console.log(success);
  },
  function(error) {
    console.error("Really helpful error:", error);
  });

(对我的完全无知,我感到抱歉.)

(I'm sorry in advance for my complete ignorance.)

推荐答案

以下是一个版本,该版本可生成一个简单的loadScript()函数,该函数返回一个promise,然后在其周围提供一个包装器,以检测是否已加载jQuery:

Here's a version that makes a simple loadScript() function that returns a promise and then provides a wrapper around it that detects whether jQuery is already loaded:

function loadScript(url) {
    return new Promise(function(resolve  reject) {
        var script = document.createElement("script");
        script.onload = resolve;
        script.onerror = reject;
        script.src = url;
        document.getElementsByTagName("head")[0].appendChild(script);
    });
}

function loadjQuery() {
    if (window.jQuery) {
        // already loaded and ready to go
        return Promise.resolve();
    } else {
        return loadScript('https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js');
    }
}


// Usage:
loadjQuery().then(function() {
    // code here that uses jQuery
}, function() {
    // error loading jQuery
});

关于代码的注释:

  1. 在您的第一个代码块中,设置一个计时器并假定在该计时器触发时将加载脚本,就像玩轮盘一样.它可能在大多数时间都有效,但是它并不是一种可靠的做事方法.另外,为了安全起见,您必须将计时器设置为比通常所需的时间更长的时间.相反,您应该基于脚本的onload回调进行触发.然后,您将确切地知道脚本何时准备就绪,并且具有100%的可靠性.

  1. In your first code block, setting a single timer and assuming that the script will be loaded when that timer fires is like playing roulette. It might work most of the time, but it is not a purely reliable method of doing things. In addition, to be safe, you have to set the timer to a longer period of time than is usually necessary. Instead, you should trigger based on the onload callback of the script. Then you will know exactly when the script is ready with 100% reliability.

在第二个代码块中,您的promise版本成功处理了已经加载jQuery的情况,但是成功处理了必须自定义加载jQuery的rejects()的情况.从我的示例中可以看到,当新加载的脚本标记完成加载后,您需要resolve()才能保证按预期工作.

In your second code block, your promise version successfully handles the case where jQuery is already loaded, but then rejects() when jQuery must be custom loaded. As you can see from my example, you need to resolve() when the newly loaded script tag has finished loading for your promise to work as desired.

这篇关于使用Promises使用JavaScript加载jQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆