Hal50000
Hal50000

Reputation: 639

Importing separate html assets from external file

Let's say I have an html page (assets.html) that has a few custom elements like buttons on it. The buttons are composed of html/css and an image.

Is it possible to import "assets.html" and 'grab' the button and clone/copy it and place it into the page that accessed assets.html?

I want to be able to have a page that has a lot of interface components, be able to load that page and grab any component I want from it.

Is it possible? What method would guarantee the css and image would be preserved with the imported html?

Upvotes: 2

Views: 1125

Answers (1)

Supersharp
Supersharp

Reputation: 31171

HTML Imports

You can use HTML Imports to import an external HTML page. Put the link in the head of your main document.

<head>
    <link rel="import" href="assets.html" id="assets">
</head>

The imported document is parsed at download (and scripts inside it are executed) but the elements are not imported in the DOM tree. Instead it is stocked in the form of an HTML Document.

Then you can grab any elements within the imported document using the import property of the <link> element. Use cloneNode(true) to get a deep copy of the imported asset.

<script>
    var importedDoc = document.querySelector( 'link#assets' ).import
    var button = importedDoc.querySelector( 'button#btn1' ).cloneNode( true )
</script>

You can the add the cloned element to the main document using appendChild().

You can also import a <style> element to get CSS assets:

document.head.appendChild( importedDoc.querySelector( 'style#st1' ).cloneNode( true ) )

Note: HTML Imports is a W3C editor's draft implemented natively in Chrome and Opera. There's a polyfill from the WebComponents.js team available for other browsers.


HTML Template

You can also import multiple elements at once by putting them in a <template> element. Clone the content property of the <template> element:

<template id="templ1">
    <style>
       #btn2 { color: red ; }
    </style>
    Name: <input id="name1">
    <button id="btn2" onclick="alert('Hello '+name1.value)">Say Hello</button>
</template>

<script>
    var template = importedDoc.querySelector( '#templ1' )
    document.body.appendChild( template.content.cloneNode( true ) )
</script>

var template = document.querySelector( '#templ1' )
document.body.appendChild( template.content.cloneNode( true ) )
<template id="templ1">
    <style>
       button { color: red ; }
    </style>
    Name: <input id="name1">
    <button onclick="alert('Hello '+name1.value)">Say Hello</button>
</template>

Upvotes: 3

Related Questions