简体   繁体   English

在浏览器和节点中动态加载JavaScript文件

[英]Dynamically loading JavaScript files in both browser and Node

My JavaScript library needs to be able to load optional scripts dynamically. 我的JavaScript库需要能够动态加载可选脚本。 I know of several ways to do this, but my library should be functional in both browsers and Node.js, and I wouldn't like to generate multiple versions. 我知道有几种方法可以做到这一点,但是我的库应该在浏览器和Node.js中都可以运行,并且我不想生成多个版本。 I also wouldn't like to reinvent the wheel. 我也不想重新发明轮子。

Is there a recommended technique for targeting both platforms with the same code? 是否有推荐的技术可以用相同的代码定位两个平台?

The browser and node.js load script files in fundamentally different ways. 浏览器和node.js以根本不同的方式加载脚本文件。 The browser requires you to add script tags or to use ajax to fetch the code and then evaluate it with eval() or a Function object. 浏览器要求您添加脚本标签或使用ajax来获取代码,然后使用eval()或Function对象对其进行求值。 node.js has require() or the code can be fetched using other node.js I/O mechanisms and then evaluate it similarly. node.js具有require()或可以使用其他node.js I / O机制获取代码,然后进行类似的评估。

There is no single way of loading code that works in both a browser and node.js. 没有一种单一的方式可以同时在浏览器和node.js中加载代码。

So, to write a single function that would load some code in either environment, you would have to detect your environment and then use the appropriate approach for the environment. 因此,要编写一个可以在任一环境中加载一些代码的函数,您必须先检测环境,然后对环境使用适当的方法。 This would not require two versions of your code, only a function that branched based on the detected environment and then executed the appropriate code for that environment. 这将不需要两个版本的代码,仅需要一个功能,该功能根据检测到的环境进行分支,然后针对该环境执行适当的代码。

This branching can be hidden behind a single function (pseduo-code): 该分支可以隐藏在单个函数(pseduo代码)的后面:

function loadLibrary(name, doneFn) {
    if (node.js detected) {
        // fetch the code using node.js I/O
        // and then evaluate the code
        // notify caller when the script has finished loading
    } else {
        // fetch the code by inserting script tags into the DOM
        // notify caller when the script has finished loading
    }
}

This would be a recommended approach for targeting both platforms with a single piece of code. 这将是建议使用单一代码针对两个平台的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM