Recommended way to "load" javascript file dependencies?
I have a priorityQueue class that depends on a set of heap functions being loaded. Currently they're in separate files, priorityQu开发者_JS百科eue.js and fheap.js. I would like to do
<script src="priorityQueue.js"></script>
and have the fheap.js file automatically loaded (order doesn't matter). Furthermore, I'd like a method that cascades (ie dijkstra.js loads priorityQueue loads fheap).
Currently each file just loads its dependencies by injecting elements at end of . Is there a better way to achieve the same result, and what should I watch out for with the current method?
Check out this question and answer for some good discussion. The short answer i believe is use jQuery because then you can do this sort of thing:
$.getScript("my_lovely_script.js", function(){
alert("Script loaded and executed.");
// here you can use anything you defined in the loaded script
});
ian.
Well you could use a library to do it for you. It is great when you don't have to reinvent the wheel and you can use something that is solid and tested. There is jQuery Lazy Plugin Loader and ensure just to name a few.
This answer might be late for you, but for those looking for the same answer, there's a lightweight JS dependency loader on git called deploader-js (also available through bower install deploader-js
) for exactly this usecase:
https://github.com/MikeSpock/deploader-js
精彩评论