问题
I'm looking for simple bullet point answers please. I've tried looking all over, Googling, other questions here but I can never find both advantages and disadvantages for each method.
回答1:
This is the answer I got from W3Schools pertaining to external javascript files
Pros
It allows separation of concerns - which is not a big deal in simple pages but as the script grows larger you can have a monolithic html page. Big files in general are not ideal for maintainability
It allows caching - when the browser loads a script externally (whether it's be from your site or a cdn) it caches the file for future use. That's why cdn's are preferred for commonly used scripts. Makes the browser use a cached script instead of building a new one every time the page loads which makes the page load faster
More readable code - this ties into the first bullet point but nevertheless it is important. The smaller the files we humans are working with the better. It is easier to catch mistakes and much easier to pass of the torch to the next developer working on the project or learning from it.
Cons
- The browser has to make an http request to get the code
There may be other browser specific reasons as well, but I believe the main reason is the separation of code into different components.
回答2:
Probably the best advantage of using external javascript files is browser caching - which gives you a good performance boost.
Imagine you have a site that uses MyJsFile.js (a random 50kb javascript file that adds functionality to your websire). You can:
- embed it in every page, and add the 50kb to every page request (not ideal)
- link it in every page (
<script src="MyJsFile.js"></script>
)
The second option is usually prefered because most modern browsers will only get the file once, and serve it from the browser cache instead of downloading it at every request.
Check out similar questions:
- Why not embed styles/scripts in HTML instead of linking?
- When should I use Inline vs. External Javascript?
- Is it better to put the JS code on the html file or in an external file?
来源:https://stackoverflow.com/questions/34707187/what-are-some-advantages-and-disadvantages-for-embedding-javascript-in-html-or-s