Using javascript to asynchronously download another javascript file.
I understand that this can be done by inserting a new script tag onto the page with the src
attribute set to the file url.
I also need to run some code when the script is finished downloading. I've been using yepnope for this and they provide "callbacks" that execute when the script has finished downloading and executing.
How is this accomplished?
Thanks!
Most JS loaders do this via injecting an
<script>
tag to the DOM, and binding itsonload
event to your provided function.yepnope
uses the same approach, and you may simply observe that from its source code. The functioninjectJs
creates a DOM element usingdoc.createElement
, setssrc
and other needed attributes usingsetAttribute
, binds theonreadystatechange
&onload
event to the provided callback, and finally inserts the element into the document.this can be done using jquery, if u want to use it, Jquery.getScript()
checkout the link it gives detail information about it.
yepnope.injectJs( scriptSource [, callback ] [, elemAttributes ] [, timeout ]);
Straight off their website: You simply run the code you need to in the successful callback like so.