Question

I am building a framework in which I have merged all JavaScript files into one file (minify).

Example:

   function A() {} function B() {}

Through minified file i want to load function asynchronous and remove from HTML when its work is done.

Example: load function A when it is required but not function B.

I have seen one framework Require.js but in that it loads JavaScript file asynchronous based on requirement.

Is there any framework which loads JavaScript functions on demand which are defined in same js file.

Was it helpful?

Solution

The downside to concatenation is you get less fine-grained control over what you are including on a given page load. The solution to this is, rather than creating one concatenated file, create layers of functionality that can be included a little more modularly. Thus you don't need all your JS on a page that may only use a few specific functions. This can actually be a win in speed as well, since having just one JS file might not take advantage of the browsers 6 concurrent connections. Moreover, once SPDY is fully adopted, one large file will actually be less performant than more smaller ones (since connections can be reused). Minification will still be important, however.

All that said, it seems you are asking for something a little difficult to pull off. When a browser loads a script, it gets parsed and executed immediately. You can't load the file then... only load part of the file. By concatenating, you are restricting yourself to that large payload.

It is possible to delay execution by wrapping a script in a block comment, then accessing it from the script node and eval()ing it... but that doesn't seem like what you are asking. It can be a useful strategy, though, if you want to preload modules without locking the UI.

OTHER TIPS

That's not how javascript works. When the function's source file is loaded, the function is available in memory. Since the language is interpreted, the functions that are defined would be loaded as soon as the source file was read by the browser.

Your best bet is to use Require.js or something similar if you want to have explicit dependency chains.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top