Using includes in html document

The Simplest Ways to Handle HTML Includes

It’s extremely surprising to me that HTML has never had any way to include other HTML files within it. Nor does there seem to be anything on the horizon that addresses it. I’m talking about straight up includes, like taking a chunk of HTML and plopping it right into another. For example the use case for much of the entire internet, an included header and footer for all pages:

That’s not real, by the way. I just wish it was. People have been looking to other languages to solve this problem for them forever. It’s HTML preprocessing, in a sense. Long before we were preprocessing our CSS, we were using tools to manipulate our HTML. And we still are, because the idea of includes is useful on pretty much every website in the world.

This will perform the include at the server level, making the request for it happen at the file system level on the server, so it should be far quicker than a client-side solution.

What’s even faster than a server-side include? If the include is preprocessed before it’s even on the server. Gulp has a variety of processors that can do this. One is gulp-file-include. That would look like this:

. @@include('./header.html') Content @@include('./footer.html') . 
var fileinclude = require('gulp-file-include'), gulp = require('gulp'); gulp.task('fileinclude', function() < gulp.src(['index.html']) .pipe(fileinclude(< prefix: '@@', basepath: '@file' >)) .pipe(gulp.dest('./')); >);

Looks like this particular plugin has fancy features where you can pass in variables to the includes, making it possible to make little data-driven components.

Handlebars.registerPartial('myPartial', '>')

There is also fancy features of this that allow for evaluation and passing data. You’ll still need a processor to run it, probably something like gulp-handlebars. Speaking of templating languages which make use of curly braces… Mustache has them, too.

Читайте также:  Java примитивные типы char

Pug is an HTML preprocessor that has a whole new syntax for HTML that is a bit more terse. It’s got includes though.

. body include ./header.html" p Content include ./footer.html" . 

If you put that in a file called index.njk , you could process it with a simple Node script into index.html like this:

const nunjucks = require("nunjucks"); const fs = require("fs"); fs.writeFile("index.html", nunjucks.render("index.njk"), function(err, data) < if (err) console.log(err); console.log("Compiled the Nunjucks, captain."); >);

Or process it with something like gulp-nunjucks. 11ty has Nunjucks built-in, along with many of the other mentioned so far. Might be good for you if you’re actually building a little site.

You could fetch the contents for the header and footer from respective files and dump the contents in.

fetch("./header.html") .then(response => < return response.text() >) .then(data => < document.querySelector("header").innerHTML = data; >); fetch("./footer.html") .then(response => < return response.text() >) .then(data => < document.querySelector("footer").innerHTML = data; >);

Speaking of JavaScript… If you’re building your site using a JavaScript framework of just about any kind, building through components is kind of the main deal there and breaking parts you want to include in other files should be no problem. Some kind of import Header from «./header.js»; and

is the territory you’d be in in React land.

  Content.  

But the content in those iframes does not share the same DOM, so it’s a bit weird, not to mention slow and awkward to style (since iframes don’t know the heights of their contents). Scott Jehl documented a cool idea though: You can have the iframe inject the content of itself onto the parent page then remove itself.

Kolya Korruptis wrote in with this adaptation which will include more than the first child of the body in case your HTML file has that:

Jekyll is a Ruby-based static site generator with includes. You keep your includes in the /_includes/ folder, then:

Jekyll is a big one, so I’m calling it out here, but there are a ton of static site generators and I’d wager any of them can do includes.

OK, I’ll call out one more SSG because it’s new and super focused. Sergey has a web components style format:

You’d name the files header.html and footer.html and put them in /includes/ and then it’ll make a build with the includes processed when you run the npm script it has you do.

But you need the right Apache configuration to allow stuff. I tried my best to get a working demo going but didn’t have much luck. I tried using .htaccess within a folder on an Apache server and flipping on what I thought was the right stuff:

Options +Includes AddType text/html .html AddOutputFilter INCLUDES .html

I’m sure there is some way to get it working though, and if you do, it’s kinda neat that it needs zero other dependencies.

Mac only, but CodeKit has a special language called Kit it processes where 90% of the point of it is HTML includes. It uses special HTML comments:

That’s a lot of ways, isn’t it? Like I said at the top, it’s very surprising to me that HTML itself hasn’t addressed this directly. Not that I think it would be a great idea for performance to have statements that trigger network requests all over our code, but it seems in-line with the platform. Using ES6 imports directly without bundling isn’t a great idea always either, but we have them. @import ing CSS within CSS isn’t a great idea always, but we have it. If the platform had a native syntax, perhaps other tooling would key off that, much like JavaScript bundlers support the ES6 import format.

Источник

HTML-импорт — include для веба: часть 1

Перевод статьи «HTML Imports #include for the web», Eric Bidelman.

От переводчика

Недавно я перевел статью по основам HTML Import. Я обещал, что если эта тема заинтересует хабра-сообщество, то переведу более подробную статью. Я решил разбить перевод на две одинаковые по размеру части, так как, по моему, на одну часть слишком много буков. Вторая часть выйдет спустя несколько дней после публикации этой части. Если, конечно, эта часть более-менее понравится хабра-сообществу.

Для чего нужен HTML-импорт?

Начало работы

В наборе стандартов Web Components есть стандарт HTML Imports, который позволяет подключение HTML-документов друг в друга. В подключаемых HTML-документах разрешается Javascript и CSS, словом, все что .html обычно содержит. Это замечательный инструмент для загрузки пакетов HTML/CSS/JS кода.

Основы

Указанный URL, это расположение импорта(import location). Чтобы использовать импорт с другого домена, его расположение должно позволять междоменное разделение ресурсов(CORS):

Примечание: браузеры игнорируют повторные запросы на один и тот же URL. Это значит, что из одного адреса будет выполнена только одна загрузка сколько бы ни было подключений на странице

Проверка на поддержку браузером
function supportsImports() < return 'import' in document.createElement('link'); >if (supportsImports()) < // Good to go! >else < // Use other libraries/require systems to load files. >

Браузерная поддержка пока на ранней стадии(прим. переводчика: оригинал статьи опубликован 11 ноября 2013, теперь, наверное, другая ситуация с поддержкой). Chrome 31 первый браузер поддерживающий HTML-импорт. Chrome 36 обновлен до последней спецификации этой фичи. Вы можете включить поддержку импорта, отметив флаг «Включить экспериментальные функции веб-платформы» по адресу

в Chrome Canary. Для других браузеров это пока не работает.

Примечание: Включение экспериментальных функций позволит использовать и другие полезные фичи веб-компонентов

Бандлинг ресурсов

HTML-импорт позволяет собирать пакеты HTML/CSS/JS кода, которые в свою очередь могут использовать другие пакеты. Этот простой, но мощный функционал, может пригодиться, если вы хотите импортированием одного ресурса предоставить другим программистам какую-то библиотеку или набор стилей. Также это полезно для поддержки модульности вашего приложения. Вы даже можете отдавать на импорт целые приложения. Только подумайте, чего можно добиться таким образом.

Вы сможете экспортировать целые пакеты веб содержимого всего одной линкой.

Bootstrap это хороший пример того, как мог бы пригодиться импорт компонентов. Бутстрап состоит из различных файлов (bootstrap.css, bootstrap.js и др.), использует JQuery (как импортируемый компонент), а в результате выдает инструменты для верстки. Разработчикам нравится возможность подключать те или иные модули, по мере необходимости. Но обычно мы идем простым путем, подключая все модули бутстрапа сразу.

Импорт был бы очень полезен при использовании таких пакетов, как Bootstrap. Вот как в будущем может выглядеть его подключение:

Нужно всего лишь добавить один линк импорта. Больше не нужно подключать кучу файлов, вместо этого весь Bootstrap завернут в файл bootstrap.html:

События load/error

Импорт всегда загружается сразу же, в порядке нахождения тега

 function handleLoad(e) < console.log('Loaded import: ' + e.target.href); >function handleError(e)

Примечание: обработчики событий загрузки/ошибки нужно объявлять перед импортом, так как браузер загружает импорт в тот момент, когда встречает тег импорта. Если на момент импорта нет обработчика загрузки, в консоли выведется ошибка undefined function.

Вы, также, можете динамически создавать импорт:

var link = document.createElement('link'); link.rel = 'import'; link.href = 'file.html' link.onload = function(e) ; link.onerror = function(e) ; document.head.appendChild(link); 

Использование содержимого импорта

Элемент импорта на странице не указывает браузеру, где размещать содержимое импорта. Он только говорит браузеру получить документ для его дальнейшего использования. Чтобы использовать содержимое импорта, нам нужно написать немного JS кода.

Вот он момент прозрения, импорт, это всего-лишь документ. На самом деле, содержимое импорта так и называется документ импорта(import document). А использовать результат импорта вы можете стандартными средствами DOM API!

link.import
var content = document.querySelector('link[rel="import"]').import; 
  • Браузер не поддерживает импорт.
  • У элемента нет атрибута rel=»import» .
    Объект не добавлен в DOM.
    Или был удален из DOM
    Ресурс не поддерживает CORS.

Полный пример

Допустим у нас есть страница warnings.html :

 
h3

Warning!

This page is under construction

Heads up!

This content may be out of date

Вы можете использовать только необходимую вам часть импортированной страницы:

  .   

Скрипты в импорте

Импорт работает не совсем, как часть документа, который его использует. Но вы, все же, можете работать с подключившей его страницей. Из импортированной страницы можно работать, как с внутренним DOM, так и с главным документом:

Пример — import.html добавляет один из своих стилей главному документу

   /* Примечание: Внутренние стили, по умолчанию применяются к импортирующему документу. Их не нужно явно добавлять в главную страницу. */ #somecontainer .  
document.currentScript.ownerDocument

мы получаем доступ к внутреннему элементу-корню импортированного документа и добавляем его кусок в главный документ (

). Это конечно бесполезный код, но нам он нужен, чтобы понять, что мы можем обращаться как к главному, так и ко внутреннему корню DOM.

Скрипты внутри импорта могут как сами исполнять код, так и предоставлять функции для выполнения в главном документе. Это похоже на модули в Питоне.

  • Код импорта выполняется в контексте содержащего его документа. Из этого исходят две удобные вещи:
    • Функции объявленные в импорте содержатся в главном объекте window .
    • Вам не нужно делать действий вроде добавления в главный документ тегов

    Источник

Оцените статью