简体   繁体   中英

Is there a downside to including javascript in html instead of linking to an external file?

I'm thinking through ways to speed up a website I'm developing. I know socket connections are expensive, so I was thinking... Is there any downside to including css and javascript code in the actual html/php source code as opposed to linking to it?

It seems that instead of making 10 calls to various files I could simply put all of the code in the html source code and not have any socket calls to external files?

I know I could put everything into 1 javascript file and call that, but that would still create a socket call.

I realize this is probably not going to make much difference and might just be a thought exercise, but is there any real downside to just inlining the code?

Different resources (ie HTML, CSS, JS, images ...) do not necessarily require a new socket connection. With HTTP/1.1 the same connection is usually used for multiple resources (but only after each other) and with HTTP/2 multiple resources can be loaded in parallel over the same TCP connection. Thus instead of trying to optimize delivery by combining HTML, JS, CSS into a single file it would be possible to optimize the transport instead by using HTTP/2.

Apart from that often resources like script, CSS and images are shared between HTML pages. In this case serving the same script etc again and again would just be wasteful. Proper caching instead enables reuse of shared resources between the pages.

And finally, inline script is considered a security problem - just look for Cross Site Scripting . Having the script separated from the content allows the use of a strict Content Security Policy which prevents such attacks.

It depends on different circumstances. For example (size of your js file).

  • If your js file size is large and having lots of codes then you should consider linking as there are many advantages -

    (i) It can be cached by the browser locally so that on next visit of the user, your website will load faster.

  • If your js file size is very small consider embedding it into HTML as it has many advantage too -

    (i) There will be less request on your server.

    (ii) If you want some variables to be assigned dynamically you should embed js in HTML because it cannot be done with linked js file.

and so on...

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