Jump to content

Including JavaScript in PHP file


LittleJoe

Recommended Posts

People always say that if you have JavaScript code which is used by multiple pages then it should be in an external page but if it is only used by a single page in should be internal. People also say that external JavaScript code can make the browsing slower since additional PHP requests are made but that when it is internal less bandwidth is used. Is it a good idea to put JavaScript code into PHP files and then include them like any other PHP files? I've been thinking about this because then I can minimise the HTTP requests and at the same time use the same JavaScript files in many PHP files.

Link to comment
Share on other sites

I'm talking about storing the JavaScript code inside PHP files (.php) and including it in your HTML/PHP files (include "javascript/menu.php") so that the contents of it appear to belong to the HTML page itself.

Edited by LittleJoe
Link to comment
Share on other sites

Someone else will need to address your specific speed question. IMO, any speed advantage would be minimal and probablly not noticable to users re: internal v external js.

Link to comment
Share on other sites

You have maybe forgotten about caching. Once a user has downloaded a js file, it will stay cached, and subsequent requests won't be made. The browser will used the cached version instead. Back in the 90s, when everyone had crappy modems and servers lived on 512K routers instead of T3 routers, small bandwidth savings mattered. Today, even if we didn't have caching, a normal HTTP request is nothing to worry about. You won't save any noticeable time at all. Most of the latency I see these days comes from slow DNS look-ups and Google Analytics. YMMV

Link to comment
Share on other sites

Most of the latency I see these days comes from slow DNS look-ups and Google Analytics. YMMV
And Facebook buttons. And Google +1 buttons. And Digg/Reddit/Yelp/any other third party buttons. And advertisements.
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...