有没有一个更简单的(本机也许?)方法,包括一个外部脚本文件在谷歌Chrome浏览器?

目前我是这样做的:

document.head.innerHTML += '<script src="http://example.com/file.js"></script>';

当前回答

你可以获取脚本作为文本,然后求值:

eval(await (await fetch('http://example.com/file.js')).text())

其他回答

var el = document.createElement("script"),
loaded = false;
el.onload = el.onreadystatechange = function () {
  if ((el.readyState && el.readyState !== "complete" && el.readyState !== "loaded") || loaded) {
    return false;
  }
  el.onload = el.onreadystatechange = null;
  loaded = true;
  // done!
};
el.async = true;
el.src = path;
var hhead = document.getElementsByTagName('head')[0];
hhead.insertBefore(el, hhead.firstChild);

你是否使用AJAX框架?使用jQuery它将是:

$.getScript('script.js');

如果您不使用任何框架,请参阅Harmen的答案。

(也许用jQuery来做这个简单的事情是不值得的(也许是值得的),但如果你已经加载了它,那么你不妨使用它。我见过一些网站加载了jQuery,例如Bootstrap,但仍然直接使用DOM API,这种方式并不总是可移植的,而不是使用已经加载的jQuery,许多人都没有意识到getElementById()在所有浏览器上都不能一致工作的事实-详情请参阅这个答案。)

更新:

我写这个答案已经有很多年了,我认为值得在这里指出的是,今天你可以使用:

SystemJS ModuleLoader jspm.io

动态加载脚本。这些可能与阅读这个问题的人有关。

参见Guy Bedford的Fluent 2014演讲:ES6模块的实际工作流程。

你可以获取脚本作为文本,然后求值:

eval(await (await fetch('http://example.com/file.js')).text())

作为上面@maciej-bukowski的回答^^^的后续,在目前(2017年春季)支持async/await的现代浏览器中,您可以按以下方式加载。在这个例子中,我们加载了load html2canvas库:

异步函数loadScript(url) { Let response = await fetch(url); Let script = await response.text(); eval(脚本); } 让scriptUrl = 'https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js' loadScript (scriptUrl);

如果你运行这个代码片段,然后打开浏览器的控制台,你会看到html2canvas()函数现在已经定义了。

在chrome中,你最好的选择可能是在开发人员工具中的源代码下的snippet选项卡。

它将允许您编写和运行代码,例如,在一个about:空白页面中。

更多信息请访问:https://developers.google.com/web/tools/chrome-devtools/debug/snippets/?hl=en