Andyjm
Andyjm

Reputation: 335

Modern JS method of PHP 'include' function

With the ever-growing library of JS frameworks (since I last build a website ~ 2014) is there a simple JS replacement/alternative for PHP's 'include' function. Or is PHP include still a relevant method of including chunks of code?

I'm building a website and want to achieve some basics like 'including' footers, headers, menu's etc. but would rather not make all my pages .php - it feels a bit clunky and unnecessary.

I found a related post here referencing Jekyll but it was a bit more specific to GitHub. Any pointers in the right direction appreciated!

Upvotes: 0

Views: 1132

Answers (1)

user268500
user268500

Reputation: 91

Since my first answer wasn't covering the interested question I decided to fully edit and replace the answer. Here we go..

Solutions

1 - JQuery load() function

<!-- LOAD JQUERY -->
<script src="http://code.jquery.com/jquery-1.12.4.js"></script>

<!-- "INCLUDE" external files with code -->
<script> 
  $("#header").load("header.html"); 
  $("#footer").load("footer.html"); 
</script>

2 - NPM gulp package which lets you includes file and pass some parameters/values

https://www.npmjs.com/package/gulp-file-include

<!DOCTYPE html>
<html>
  <body>
  @@include('./header.html')
  @@include('./main.html')
  </body>
</html>

an example of a gulp task:

var fileinclude = require('gulp-file-include'),
    gulp = require('gulp');

    gulp.task('html', function() {
        return gulp.src(['./src/html/views/*.html'])
            .pipe(fileInclude({
                prefix: '@@',
                basepath: 'src/html'
            }))
            .pipe(gulp.dest('./build'));
    });

3 - pure javascript via document.write function and including script with it via src

<script type="text/javascript" src="header.js"></script>

4 - pure ajax request that requests additional data and places it where it should be placed on the page

5 - SSI (Server Side Include), as I mentioned it in comment

6 - iframes (not the best way, though)

7 - asp/jsp server script include (as alternative to php server script include)

More info here:

Common Header / Footer with static HTML

Make header and footer files to be included in multiple html pages

Hopefully you can find the best way that will suit your needs from one of this.

Upvotes: 1

Related Questions