问题描述
我编写了JavaScript库,以使用 FileSaver.js 及其关联库.但是,我不想总是在有人要使用我的库时加载FileSaver.js.而且我不想强迫他们使用script
标签本身加载所有与FileSaver相关的所有JavaScript库(甚至加载我的其中一个库).
I wrote JavaScript library to use FileSaver.js and its associated libraries. However, I don't want to always load FileSaver.js whenever someone wants to use my library. And I don't want to force them to load all the various FileSaver related JavaScript libraries with script
tags themselves (or even load one of mine which would do that).
相反,我更喜欢这样的事情.当他们调用我的createImage
函数时,它首先执行以下操作:
Instead, what I'd prefer is something like this. When they call my createImage
function, it first does the following:
function createImage(image, name) {
if (typeof(saveAs) !== 'function') {
var element = document.createElement('script');
element.async = false;
element.src = 'FileSaver.js';
element.type = 'text/javascript';
(document.getElementsByTagName('head')[0]||document.body).appendChild(element);
}
// now do the saveImage code
}
问题是,在上述之后,saveAs
函数仍未定义. 之后,我的createImage
完成才是saveAs
函数的最终定义.
Problem is, after the above, the saveAs
function is still not defined. It's only after my createImage
completes is the saveAs
function finally defined.
推荐答案
整体解决方案是使用模块系统. AMD(在我看来,请不要启动一个神圣的战争观点)可能是最常用的浏览器异步代码加载系统. AMD只是一个规范,但是 require.js 之类的东西是使用AMD模块的非常流行的工具.
the Holistic solution is to use a module system. AMD is (in-my-just-an-observation-please-dont-start-a-holy-war-opinion) probably the most commonly used system for browser async code loading. AMD is just a spec, but something like require.js is a very popular tool for using AMD modules.
这样的想法是,您可以定义模块之间的依赖关系,如果需要,require.js将获取它们.总体思路是模仿其他语言(如Java,C#或python)的导入/命名空间功能.我认为是代码共享"这个词吗?
The idea being that you can define dependencies between your modules, and require.js will go fetch them if need be. The general idea is to mimic the import/namespace functionality of other languages (like java, C#, or python). "code sharing" i think is the term?
只需将所有代码放入一个在加载依赖项后便运行的回调函数中,因此可以确保存在所需的对象和方法.
simply put you have all your code in a callback function that runs once the dependencies are loaded, so you can be sure the needed objects and methods are present.
更新2015年
只是一个附录.尽管上面的信息仍然正确,但是前端代码管理正朝着Webpack和Browserify之类的解决方案迅速发展,这些解决方案将任何模块类型的代码捆绑并连接在一起,并且都具有动态代码加载功能(Webpack称之为代码拆分).再加上依赖管理的npm指数增长,开始使AMD的相关性降低.
just an addendum. while the info above is still correct, front end code management is moving quickly toward solutions like Webpack and Browserify, which bundle and concatenate code of any module type and both have dynamic code loading capabilities (webpack calls this code splitting). That coupled with the exponential growth of npm for dependency management is beginning to make AMD less relevant.
这篇关于动态加载的JavaScript库何时可用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!