简体   繁体   中英

Script src vs script in page code

I have 7000 line js script. What is better putting the script in page like <script src="myscripts.js"></script> or putting like <script>my script blah blah blah</script>

It's almost always more efficient to use external js files with proper caching headers so that the client only has to download it once rather than every time they visit/reload the page.

More efficient in multiple ways:

  • Faster overall load times
  • Easier to work on the code (less hours spent maintaining)
  • Easier to diagnose code problems (less hours spent maintaining)
  • Easier to minify the code (less hours spent maintaining)

If this forms a library of functions that are used throughout the site, you are better off with it being an referenced script tag. If it is specific to the page, leave it on the page.

With it being referenced, you get the benefit of the server caching the included page, and the browser not pulling it down multiple times if nothing has changed.

A good web programming practice is to separate your Model(HTML), View(CSS) and Controller(JS), so called front end MVC.

You might also what to check out this wiki for more detailed explanation on why should you keep your JS separate from your Models.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM