Search code examples
javascriptphphtmlclient-sideserver-side

Is PHP include() or JS src to include file faster?


Sometimes when I need to include the same group of elements in many web pages, I use PHP:

<?php include "somefile.html" ?>

When somefile.html is this:

<h1>TITLE</h1>
<h2>Subtitle</h2>

And sometimes, when I'm too lazy to use PHP and turn on my local server, I use JS:

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

When somescript.js is like this:

document.write(
    "<h1>TITLE</h1>" +
    "<h2>Subtitle</h2>"
);

The second version is just a tiny bit more inconvenient, but I use both ways.

However, I was wondering which way is customary and which way is faster.

I know PHP is server-side and is pre-parsed into HTML first, but even though it loads before the JS does, I don't know if it's faster. Because JS is client-side, it is parsed by the browser and might be quicker than sending a request to the server (although I'm not totally sure - tell me if I'm making incorrect inferences).

Feel free to tell me if I'm unclear and redirect me to another page that could help.

Thanks.


Solution

  • The second way is not only worse performance wise, it's an awful practice that could potentially erase your entire page because of how document.write() works. You shouldn't be using document.write() unless you are VERY sure you need to, which is rare. The only case I know of in which it is acceptable is for fallbacks of cdn delivered javascript. You use it to write in script tags for a local copy, like this:

    <script src="http://code.jquery.com/jquery-latest.js"></script>
    <script>window.jQuery || document.write('<script src="sys/lib/jquery.js"><\/script>')</script>
    

    Consider that the script you're including is on the server, so a request has to be sent for it and it must be loaded before the page can continue or finish loading. The server could have just sent that data to begin with.