在Quora上发现的一段Js,求高人出来解答它的作用,最好还能分析一下它的作用

mywaiting
  • 133

翻看Quora前端的Js,发现一段很奇怪的代码,长得很像"require.js",但又不完全是,在Chrome下面查看源代码,链接view-source:http://www.quora.com/,最前面的script,粘贴如下,求各种解答,最好能够分析一下它的实现和作用。貌似Quora使用这个东西组织了它全部的Js代码,求解答。

代码粘贴如下(经过美化):

this.require ||
function(a, b, c) {
    function q() {
        if (!i) try {
            while (g !== h && p(g.next)) i = g,
            g = g.next,
            g(g.require)
        } finally {
            i = 0
        }
    }
    function require(a) {
        if (!f[a]) {
            var b = e[a];
            b && p(b, a) && b(b.require, f[a] = {},
            b)
        }
        return f[a]
    }
    function p(a, b, c) {
        var d, f = {},
        g = n(a, b);
        c = c || {};
        for (b in g) c[b] || (c[b] = a = e[b], a && p(a, b, c) ? f[b] = 1 : d = 1);
        for (b in f) delete g[b];
        return ! d
    }
    function o(a) {
        var c = require("settings");
        if (!d[a] && !e[a] && c.requireBase) {
            var f = b.createElement("script");
            f.src = c.requireBase + a + ".js",
            f.async = d[a] = !0,
            f.charset = "utf-8";
            try {
                f.addEventListener("load", q, !1)
            } catch(g) {
                f.attachEvent("onreadystatechange",
                function() { / loaded | complete / .test(f.readyState) && q()
                })
            }
            b.documentElement.appendChild(f)
        }
    }
    function n(a, b) {
        if (!a.unmet) {
            var c = a + "",
            d, e = a.unmet = {};
            j.lastIndex = 0;
            while (d = j.exec(c)) e[m(d[1], b)] = 1
        }
        return a.unmet
    }
    function m(a, b) {
        if (b && /^\./.test(a)) {
            a = "/" + b + "/../" + a;
            while (a != (b = a.replace(k, "/"))) a = b
        }
        return a.replace(/^\//, "")
    }
    function l(a) {
        throw a
    }
    var d = {},
    e = {},
    f = {},
    g = {},
    h = g,
    i, j = /require\(['"]([^'"]+)['"]\)/g,
    k = /\/(\.?|[^\/]+\/\.\.)\//;
    require.install = function(a, b) {
        e[a] || (e[b.id = a] = b, (b.require = function(b) {
            return require(m(b, a)) || l(b)
        }).later = function(b) {
            o(m(b, a))
        },
        q())
    },
    require.enqueue = function(a) { (a.require = function(a) {
            return require(a) || l(a)
        }).later = o,
        p(h = h.next = a) && g.next === h && q()
    },
    require.later = o,
    a.require = require
} (this, this.document);
回复
阅读 3.6k
1 个回答

应该是一个 commonjs 的简单实现

require 引入模块
require.install 注册模块

那几个函数也只能猜测其用途,这样要搞清楚来龙去脉还真难。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
宣传栏