我可以使用`fetch`从另一个运行JS脚本吗? [英] Can I run a JS script from another using `fetch`?

查看:192
本文介绍了我可以使用`fetch`从另一个运行JS脚本吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这里降低中级JS / JQ人。

Lower intermediate JS/JQ person here.

我试图通过使用JS fetch来逃避回调地狱。这被称为AJAX的替代品,似乎非常强大。我可以看到你如何用它来获取HTML和JSON对象......但是它能够运行你所在的另一个JS脚本吗?也许ES6中还有另一个新功能:

I'm trying to escape callback hell by using JS fetch. This is billed as "the replacement for AJAX" and seems to be pretty powerful. I can see how you can get HTML and JSON objects with it... but is it capable of running another JS script from the one you're in? Maybe there's another new function in ES6 to do:

$.getScript( 'xxx.js' );

ie

$.ajax({ url : 'xxx.js', dataType : "script", });

...?

之后,回应Joseph The Dreamer:

later, response to Joseph The Dreamer:

试过这个:

const createdScript = $(document.createElement('script')).attr('src', 'generic.js');
fetch( createdScript )...

...它没有运行脚本generic.js。你的意思是什么吗?

... it didn't run the script "generic.js". Did you mean something else?

推荐答案

Fetch API应该提供基于promise的API来获取远程数据。加载随机远程脚本是而不是 AJAX - 即使 jQuery.ajax 能够做到这一点。它不会被Fetch API处理。

Fetch API is supposed to provide promise-based API to fetch remote data. Loading random remote script is not AJAX - even if jQuery.ajax is capable of that. It won't be handled by Fetch API.

脚本可以动态附加并包含一个承诺:

Script can be appended dynamically and wrapped with a promise:

const scriptPromise = new Promise((resolve, reject) => {
  const script = document.createElement('script');
  document.body.appendChild(script);
  script.onload = resolve;
  script.onerror = reject;
  script.async = true;
  script.src = 'foo.js';
});

scriptPromise.then(() => { ... });

SystemJS应该为脚本加载提供基于承诺的API,也可以使用:

SystemJS is supposed to provide promise-based API for script loading and can be used as well:

System.config({
  meta: {
    '*': { format: 'global' }
  }
});

System.import('foo.js').then(() => { ... });

这篇关于我可以使用`fetch`从另一个运行JS脚本吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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