有没有一个更简单的(本机也许?)方法,包括一个外部脚本文件在谷歌Chrome浏览器?
目前我是这样做的:
document.head.innerHTML += '<script src="http://example.com/file.js"></script>';
有没有一个更简单的(本机也许?)方法,包括一个外部脚本文件在谷歌Chrome浏览器?
目前我是这样做的:
document.head.innerHTML += '<script src="http://example.com/file.js"></script>';
当前回答
我用这个在控制台加载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>");
其他回答
在现代浏览器中,您可以使用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 */ })
我用这个在控制台加载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>");
在chrome中,你最好的选择可能是在开发人员工具中的源代码下的snippet选项卡。
它将允许您编写和运行代码,例如,在一个about:空白页面中。
更多信息请访问:https://developers.google.com/web/tools/chrome-devtools/debug/snippets/?hl=en
你可以获取脚本作为文本,然后求值:
eval(await (await fetch('http://example.com/file.js')).text())
你是否使用AJAX框架?使用jQuery它将是:
$.getScript('script.js');
如果您不使用任何框架,请参阅Harmen的答案。
(也许用jQuery来做这个简单的事情是不值得的(也许是值得的),但如果你已经加载了它,那么你不妨使用它。我见过一些网站加载了jQuery,例如Bootstrap,但仍然直接使用DOM API,这种方式并不总是可移植的,而不是使用已经加载的jQuery,许多人都没有意识到getElementById()在所有浏览器上都不能一致工作的事实-详情请参阅这个答案。)
更新:
我写这个答案已经有很多年了,我认为值得在这里指出的是,今天你可以使用:
SystemJS ModuleLoader jspm.io
动态加载脚本。这些可能与阅读这个问题的人有关。
参见Guy Bedford的Fluent 2014演讲:ES6模块的实际工作流程。