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

目前我是这样做的:

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

当前回答

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);

其他回答

在现代浏览器中,您可以使用fetch来下载资源 (Mozilla docs)然后eval来执行它。

例如,要下载Angular1,你需要输入:

fetch('https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js')
    .then(response => response.text())
    .then(text => eval(text))
    .then(() => { /* now you can use your library */ })

安装tampermonkey并添加以下UserScript,带有一个(或多个)@match和特定页面url(或所有页面的匹配:https://*)):

// ==UserScript==
// @name         inject-rx
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  Inject rx library on the page
// @author       Me
// @match        https://www.some-website.com/*
// @require      https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.4/rxjs.umd.min.js
// @grant        none
// ==/UserScript==

(function() {
    'use strict';
     window.injectedRx = rxjs;
     //Or even:  window.rxjs = rxjs;

})();

当您需要控制台中或代码片段上的库时,请启用特定的UserScript并刷新。

这种解决方案可以防止名称空间污染。您可以使用自定义名称空间来避免意外覆盖页面上现有的全局变量。

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);

我用这个在控制台加载ko knockout对象

document.write("<script src='https://cdnjs.cloudflare.com/ajax/libs/knockout/3.5.0/knockout-3.5.0.debug.js'></script>");

或本地托管

document.write("<script src='http://localhost/js/knockout-3.5.0.debug.js'></script>");

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

$.getScript('script.js');

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

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

更新:

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

SystemJS ModuleLoader jspm.io

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

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