3 ms·
On-Demand Loading of JavaScript Logic Via AJAX to Increase Speed
- byoung2 16y agoIs there a reason to use AJAX to write the new JavaScript instead of just dynamically appending a script tag? jQuery handles the latter very nicely. For example, you can use the .html() method to write in the new script tag, with jQuery evaluating the code and then discarding it. You can keep rewriting new script tags into the same container this way.
- NathanKP 16y agoIf you dynamically append the script tag you still have to get the script from somewhere. Hence my library loads the script via AJAX. Rather than using the roundabout technique of writing another tag, it uses eval() to evaluate the downloaded JavaScript directly.
- byoung2 16y agoRather than using the roundabout technique of writing another tag This isn't so roundabout: var path = 'http://www.domain.com/script.js'; $('#code').html('<script type="text/javascript" src="'+path+'">'); jQuery loads the script, evaluates it, then discards it.
- NathanKP 16y agoTo me it seems a little bit more obscure than just loading the JavaScript and the performing an eval() on it. My other problem is that it discards the script. If you replace the contents of #code, perhaps by loading another script it would also delete the existing script, right?