这个javascript动态文件include系统有什么问题吗

Is there anything wrong with this javascript dynamic file include system?

本文关键字:什么 问题 系统 include javascript 动态 文件 这个      更新时间:2023-09-26

代码:

function stop(reason){
    throw(reason);
}
function pragma_once(file_name){
    if(window[file_name] !== undefined)
        stop("Duplicate symbol: "+file_name);
    window["__INCLUDE__"+file_name]=true;
    return true;
}
function include(file_name){
    var x = document.createElement('script');
    x.src = file_name;
    document.getElementsByTagName("head")[0].appendChild(x);
}

我一直在使用node.js,require()对于保持代码的整洁、更易于跟踪和阅读似乎非常有用。但正如我所注意到的,用于web的javascript并没有"require()"。我找到了requirejs,它为web javascript添加了require()功能。但我不知道使用库对于一项看似很小的任务是否有用。所以我写了一些类似require(更像c#include)的东西。我注意到的唯一真正的问题是它异步加载所有内容。这不是最终版本,但它的功能不会改变。

是否存在我不知道的潜在问题?有什么理由不使用这个吗?

我认为人们告诉别人不要这样做的主要原因是因为这三个原因。

  1. 它为这个脚本发出另一个HTTPGET请求,并且它不在页面的初始加载过程中。

  2. 根据我所看到的内容,可以多次包含同一个文件。

  3. 如果您需要该功能,那么可以在web框架或扩展Javascript的脚本语言中找到更优化的版本。