Search code examples
javascriptjquerygetscript

Should I use jQuery's getScript() or tons of <script> tags?


I have developed a JavaScript system that's broken up into a bunch of files (somewhere around 20-25). Most of them are core files and need to be present in order for the system to function, but some act as plugins and can be omitted if the functionality isn't required.

My concern is that I have a bunch of HTML pages using this system with different combinations of plugins, all of them with this huge wall of <script> tags at the start of the page that needs to be carefully ordered so all dependencies of a file are loaded first. It feels like it's just a matter of time before I or someone else messes up the copy/pasting of these tags between the HTML files and stuff breaks.

So, I've been looking into jQuery's getScript() feature and thought about creating a setup file that takes a few parameters specifying the combination of plugins to use and then dynamically loads everything behind the scenes, reducing it all to a single <script> tag per file (not counting jQuery etc.)

Are there any important downsides to this? Presumably, loading would take longer due to jQuery initialization and so on, but is that likely to be significant? Additionally, is getScript potentially insecure for cross-file dependencies in the event that the dependent finishes downloading before its dependency? Are there perhaps browser compatibility issues to take into consideration too?

I really want to clean up this wall of tags, so if anyone with more experience can help me out here, it'd be greatly appreciated.


Solution

  • You should look at Require.js, or any other javascript module loader. This lib can help you load only that scripts, what you need on current page/part of your app. If you do not want to use any javascript loader <script> way is a faster a bit, but it's not so important.