Would it be faster include a javascript file and outputting it in the html as a <script>
or just use the src
attribute and let the browser make another request?
Simply outputting it instead of letting the browser make another request would obviously mean less requests and possibly less server load, but does it make it faster? Including the files and outputtin开发者_StackOverflow中文版g them doesn't let the browser cache them.
If you include it, every different page will have the overhead of downloading the script again.
If you externally link to it, and send future expiry headers and use versioning with a cache buster (for changes), your file will be downloaded once as per required. On the topic of performance, be sure to minify or pack your production use JavaScript.
Of course, this is very relevant to your JavaScript. If it is a few lines and likely not to change, maybe you could save that one HTTP request and place it inline.
99% of the time, however, in an external file is best practice.
It is quite a complex answer. Obviously the techniques differ for a production enviroment and a development one.
The last one is quite simple: let include your scripts as they are.
For production environment: you should concatenate the js files you need into one file, minify and compress it. You can retrieve libraries from public cdn to increase download performance and relieve your server load.
The increased server load (the http header) should be balanced by the caching
To increase the user-perceived performance you should link your js file at the bottom of the page instead that into the head section
You should be aware of the deferred execution too, it let the browser to download other resources while downloading javascript files (by default the browsers download a javascript at a time as it doesn't know if the javascript he download will change the dom during his execution).
At last, if your script is quite short you will have a better performance if you include it right into the web page
At the very last, if you have similar question, you should enjoy reading this: http://developer.yahoo.com/performance/rules.html
I agree with @alex. Also, linking allows the script files to be downloaded in parallel as the page is being parsed. Most browsers use multiple threads to download content while parsing the main page's content.
精彩评论