Permalink
Browse files

working implementation and example

  • Loading branch information...
substack committed Feb 16, 2012
0 parents commit 2f36d6d283d7992d68e33a154718ed6ae63639b5
Showing with 94 additions and 0 deletions.
  1. +4 −0 example/index.html
  2. +1 −0 example/js/beep.js
  3. +1 −0 example/js/boop.js
  4. +5 −0 example/js/entry.js
  5. +5 −0 example/server.js
  6. +78 −0 src/wreq.js
@@ -0,0 +1,4 @@
+<script src="/wreq.js"></script>
+<script src="/js/entry.js" type="text/wreq"></script>
+
+<div id="res">[]</div>
@@ -0,0 +1 @@
+module.exports = 'beepity'
@@ -0,0 +1 @@
+module.exports = 'boop!!!'
@@ -0,0 +1,5 @@
+var beep = require('./beep.js');
+var boop = require('./boop.js');
+
+var elem = document.getElementById('res');
+elem.innerHTML = beep + ' ' + boop;
@@ -0,0 +1,5 @@
+var express = require('express');
+var app = express.createServer();
+app.listen(8000);
+
+app.use(express.static(__dirname));
@@ -0,0 +1,78 @@
+var detective = require('detective');
+var http = require('http-browserify');
+var path = require('path');
+
+function load (file) {
+ fetch(path.resolve(window.location.pathname, file), function (src) {
+ src.run();
+ });
+}
+
+(function () {
+ function onready () {
+ if (document.readyState === 'loading') return;
+ document.removeEventListener('readystatechange', onready);
+ var scripts = document.querySelectorAll('script[type="text/wreq"]');
+ for (var i = 0; i < scripts.length; i++) {
+ if (scripts[i].src) {
+ var file = scripts[i].src.replace(/^https?:\/\/[^\/]+/, '');
+ load(file);
+ }
+ else {
+ var file = '#' + Math.random().toString().slice(2);
+ store(file, scripts[i].innerHTML, function (src) {
+ src.run();
+ });
+ }
+ }
+ }
+ onready();
+ document.addEventListener('readystatechange', onready);
+})();
+
+var sources = {};
+
+function run (src) {
+ if (src.cache) return src.cache;
+
+ var fn = Function([ 'require', 'module', 'exports' ], src.source);
+ var m = { exports : {} };
+ fn.apply(null, [
+ function require (p) { return src.requires[p].run() },
+ m, m.exports
+ ]);
+ return m.exports;
+}
+
+function fetch (file, cb) {
+ if (sources[file]) return cb(sources[file]);
+ sources[file] = {};
+ var opts = { path : file };
+
+ http.get(opts, function (res) {
+ var data = '';
+ res.on('data', function (buf) { data += buf });
+ res.on('end', function () {
+ store(file, data, cb);
+ });
+ });
+}
+
+function store (file, data, cb) {
+ var requires = detective(data);
+ var pending = requires.length;
+ sources[file].source = data;
+ sources[file].requires = {};
+ sources[file].run = function () {
+ return run(sources[file]);
+ };
+
+ if (pending === 0) cb(sources[file]);
+
+ requires.forEach(function (r) {
+ fetch(path.resolve(path.dirname(file), r), function (src) {
+ sources[file].requires[r] = src;
+ if (--pending === 0) cb(sources[file]);
+ });
+ });
+}

0 comments on commit 2f36d6d

Please sign in to comment.