browserify / browserify-handbook

how to build modular applications with browserify

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Loading bundle aynchronously

sassanh opened this issue · comments

It's stated here https://github.com/substack/browserify-handbook#partitioning that:
"You could also load the bundles asynchronously with ajax or by inserting a script tag into the page dynamically"

I wonder how? If I load another bundle dynamically how can I require a file bundled in it? If I try to require it, I'll get Uncaught Error: Cannot find module 'x' because the require function doesn't know about files bundled in it.

I was able to achieve this using external instead of exclude (the document linked above uses exclude) and omitting -s ... and just using -r (the document uses -s) as described here:
http://stackoverflow.com/questions/29222745/how-do-i-exclude-the-requirereact-from-my-browserified-bundle

@sassanh I am researching lazy-loading code-split bundles with Browserify and I'm curious about your findings. Have you arrived at any better conclusion than the one you found here? Would you mind explaining it in more detail to me?

@jessehattabaugh that stackoverflow thread explains it all. I'm stilling using this same method and except one problem it's totally satisfying my needs. The only problem is some code may appear in few bundles. But that problem can be solved by using -x and -r more wisely and probably developing a task manager that generates -xs and -rs. Suppose this example:

a.j:

var b = require('./b.js');
var c = require('./c.js');

b.js:

var d = require('./d.js');

c.js:

var d = require('./d.js');

d.js:

// 100000 lines of code

Now suppose that you create 3 bundles:

> browserify -x b.js -x c.js a.js > bundle-a.js
> browserify -r b.js > bundle-b.js
> browserify -r c.js > bundle-c.js

Now the problem is 100000 lines of code in d.js appear in both bundle-b.js and bundle-c.js. In many cases the developer may prefer it the way it is because for example there's no guaranty that when b or c are loaded, the other one is loaded in browser too. An alternative would be to create a bundle-d.js and use it first time b or c loads and when the other wants to load use the same d. Another alternative would be to include b only in d because we're sure b loads before c. Or maybe some more alternatives. All of these can be handles by changing -xs and -rs but when you have a complicated dependency graph it'll be so hard to handle it all by yourself. Currently I'm letting my bundles include duplicate code as I don't have time to spend on this but if I find the time some day I'm gonna develop a tool that takes a description of dependency graph which includes information discussed above (such as whether there's a guaranty b is loaded before c, etc) and generates -xs and -rs.