This is an example I use in real life, trimmed down to the very basics. (I checked it in a browser just in case I broke something with the trimming -- it works fine.)
XMLHttpRequest always had problems with local filesystems (because there's no http transfers), so you probably want to test in on a local web server before moving on to other stuff, modifying, etc.
In index.htm you'll find a <script> tag in the head linking to merger.js, and another one triggering the function LoadExternal later in the body. The latter is not necessary if you enable window.addEventListener at the end of merger.js to trigger LoadExternal when the body ends loading -- it is only there to speed up loading external stuff and avoid the waiting.
You'll see the LoadExternal function in merger.js looks for an <a> element with the id "retrieveme" (external.htm in this case), and sets the target for download, with the function InjectExternal to be executed when the data arrives. It is InjectExternal the one that does the real replacement by looking
again for #retrieveme.
While LoadExternal should be easy enough to modify to retrieve more files from different elements' pointers, the current InjectExternal doesn't know what element it was invoked on/it must replace when injecting its data, hence the initial lookup. If you were to invoke it several times, you should devise a way to connect target elements and downloaded data sets before replacing like crazy.
Hope this helps
- merger.zip 2.1 kB