开发者

Best Way to Organize JavaScript Files

开发者 https://www.devze.com 2023-02-02 09:35 出处:网络
So I have web app with multiple JS files (jQuery, jQuery, my own JS code and more). Say I have a page named index.html. What would be the best practice to include / preload my js files? I was thinking

So I have web app with multiple JS files (jQuery, jQuery, my own JS code and more). Say I have a page named index.html. What would be the best practice to include / preload my js files? I was thinking about creating a separate JS file that will do the preloading (include all the other scripts and call jQuery.noConflict()). What do you guys suggest? Is this possible? How would you impl开发者_如何学运维ement it?

Thanks!


In general, combine your script files into one file (and minify or compress them, or even compile them, but note that this last item is not zero-impact, there are pain points). See notes here and here. Basically, one of the first guidelines you'll see for a good fast page load is "minimize HTTP requests." So you don't want six separate script tags where you could have one.

For popular scripts, though, you may benefit from using them from Google's CDN. Google is kind enough to host most popular JavaScript libraries on their CDN for free. The advantage here being not only that the CDN will be fairly fast, but that the target user's browser may well have a cached version of the script you want to use even though they've never been to your site before.


Check out RequireJS, a smart and robust script loader for JavaScript. It's designed to work well with jQuery and comes with an optimization tool to combine all of your scripts into one.


The best way is to minimize all the js files and combine them into one script. This will cause less work for the browser, as it doesn't have to make multiple requests to the server.


If you are going to load everything up at the same time, you could put it all into a single compressed file

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号