Chrome扩展程序中有多个JS文件-如何加载它们? [英] Multiple JS files in Chrome Extension - how to load them?
问题描述
我写了一个Chrome扩展程序.我的background.js文件很大,因此我想将其拆分为较小的部分,并在需要时加载指定的方法(某种形式的延迟加载).
I've wrote a Chrome Extension. My background.js file is quite large, so I want to split it to smaller parts and load specified methods when required (some kind of lazy-loading).
我已经使用Firefox完成了此操作:
I've done this with Firefox:
// ( call for load specified lib )
var libPath = redExt.basePath + 'content/redExt/lib/' + redExt.browser + '/' + libName + '.js';
var service = Components.classes["@mozilla.org/moz/jssubscript-loader;1"].getService(Components.interfaces.mozIJSSubScriptLoader);
service.loadSubScript("chrome://" + libPath);
// ( executing loaded file )
是否有可能在基于Webkit的浏览器中以类似方式进行操作?我已经找到了有关如何将多个JS文件注入到匹配页面中的解决方案(使用manifest.json
),但是找不到用于扩展以包含JS文件的方法.
Is there any possiblity to do it similar way in Webkit-based browsers? I've found solutions for how to inject multiple JS files into matching pages (using manifest.json
) but cannot find way to include JS file just for extension.
推荐答案
找到了可能的解决方案.有一个RequireJS main方法的简单实现,该方法使用JavaScript回调跟踪来查找加载主扩展文件的事件,并通过扩展上下文绑定执行该方法. https://github.com/salsita/browser-require/blob/master /require.js
Found possible solution. Theres a simple implementation of RequireJS main method require which uses JavaScript callback trace to find event for loading main extension file and binds executes it with extension context. https://github.com/salsita/browser-require/blob/master/require.js
似乎可行,但是此解决方案有一些缺点:
It seems to work, but this solution has a few cons:
- 在第1行,第1列"中报告了错误报告,因为此解决方案将代码直接注入
func.call
-调试非常困难 - 已加载的JS文件未出现在控制台/chromebug中
- 如果当前选项卡使用HTTPS,Chrome将不允许逃避脚本,尤其是从本地上下文(
file:///
)逃避脚本,因此有时无法按预期运行
- bug reports are reported in "line 1, column 1" because this solution injects code directly to
func.call
- debugging is very hard - Loaded JS files does not appear in console / chromebug
- If current tab uses HTTPS Chrome will disallow evaling scripts, especially this from local context (
file:///
), so it sometimes just dont work as expected
这篇关于Chrome扩展程序中有多个JS文件-如何加载它们?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!