2

I usually have the Javascript or Jquery of my web apps in external files that I link to from index.html. Using:

<script src="../js/somple.js"></script>

I have notice most applications link to js the same way but it seems to be a common practice to also have some of the JavaScript in the same index page. (either on header section or at the bottom of the page)

Such as:

<script type="text/javascript"> 
   ......
</script>

My question:

In what cases could I benefit from keeping the JavaScript in the same file?

I understand having the Javascript at the bottom of the page as opposed to having it enclosed on header allows html contend to load first, but what about placing the JS externally? I just want to learn about good practices and load speed/efficiency regarding the location of JS.

4

1 回答 1

3

A frequent good practice is

  • to have in the external files everything that is a library or at least can be used in more than one page
  • to have in your page the code that is specific to your page, as long as it isn't too long to hinder readability

This way you ensure coherency, readability and performances (minimal number of requests).

Personally, I also like to keep my external files "silent" : they do nothing unless called, and the script at the bottom of my page calls them. Often this script is similar to this :

<script>
   MyApp.init({someBasic:"option"});
</script>

example

于 2013-10-09T07:54:39.867 回答