-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Client side include feature for HTML #2791
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
I personally do not buy this much (sorry!), as we have enough primitives ( |
How would this differ from HTML Imports? |
HTML Imports load a HTML document, via This idea is about inserting HTML snippet in HTML document. e.g. main document <include src="header.html"></include>
Awesome contents
<include src="footer.html"></include> header.html <h1>Welcome!</h1> footer.html <footer>Copyright 2017 by me</footer> will result in <h1>Welcome!</h1>
Awesome contents
<footer>Copyright 2017 by me</footer> |
I was always dreaming to see this feature in the browser. This tag, as exposed by @TakayoshiKochi should allow to put some HTML content in the DOM in a simple way. I think the I would like to propose the following: <include id="my-include" src="an_URL.html"></include> And the event could be: var included = document.querySelector('#my-include');
included.addEventListener('load', e => {
// ...
});
included.loaded.then((included_) => {
// here you see that
// included_ === included
// and this promise is ready once the HTML code
// from included.src has been fetched and appended to the DOM
}); Reproducing the behavior from So, an include has a small set of features
Hope this idea will be useful. |
There are some questions around this tag that I'd like to expose too.
<include src="an_URL.html">
<div class="preloader">...</div>
</include> After fetching, the innerHTML content should be replaced?
|
I don't think we should do this. The user experience is much better if such inclusion is done server-side ahead of time, instead of at runtime. Otherwise, you can emulate it with JavaScript, if you value developer convenience more than user experience. I'd encourage anyone interested in this to create a custom element that implements this functionality and try to get broad adoption. If it gets broad adoption we can consider building it into the platform, as we have done with other things like jQuery -> querySelectorAll. |
@domenic I tried to develop this idea as a custom element for my projects, and found that it's possible to achieve HTML import, but there are some things that made that solution hard to debug. For instance, beforescriptexecute was removed or even not implemented. Because of that I was forced to turn all my scripts into "inline" scripts. I'll keep on spreading the word with more cases about how to split the code into small pieces without using extra JS effort. |
What's the actual purpose of this? As domenic mentioned, you can already do this quite easily server-side, so why do we need an HTML element to do it less effectively? |
Personally, I found this feature very useful in my projects. But, this is only my personal opinion. And, what @domenic said sounds fair. The only thing that I'd like to repeat is the absence of I'll be happy to share with you @Yay295 or anybody else my experience with this feature, the pros and cons, but that chat should be outside this issue. |
I think it would be quite useful for any cases where we want DRY html authoring but not the burden of running code server side or requiring JS. It's actually what I naively expected html imports to do at first. The use cases may be relegated primarily to the realm of small, static-only websites but I think it's a huge advancement for those cases. Simple static-only sites are a large number of websites, or sites that probably should be purely static but cannot be for reasons such as requiring server side rendering to DRY shared fragments such as header/footer, etc. I'm thinking of all the shared web hosting site builder tools and a large number of wordpress sites (a security/maintenance nightmare for typical site owners in my experience) and things along those lines. These kinds of sites are typically owned/maintained by the least tech-savvy operators and are therefore likely under-represented in these kinds of platform-advancement discussions. I'm aware that dynamic rendering or static build tools can get the job done, but those are inaccessible tools to a majority of simple website owners (again, in my personal experience). The JS-free aspect gets back into the philosophy of progressive enhancement including "site basically works without scripting enabled" and I think that's still important, personally, particularly when we have Brave browser picking up steam with JS disabled by default for security/privacy purposes. I may try to take a stab at faking this using a custom element backed by fetch, but it wouldn't fill the same gap IMHO and would merely be a demonstration for illustrating the convenience it can provide to the page authoring experience once it's all set up. |
I might also comment that I would expect client side includes to do something efficient with caching based on server headers or whatever, minimizing the UX cost of the extra round trips after first load (and I would presume we could also use link rel=preload etc. to great effect for load time beyond the first page). With http/2 implemented appropriately the UX cost of this feature should go away entirely. |
I want to jump in and mention that PHP (Personal Home Page) was literally created to solve this problem "In the most simple way possible". This could be simply done on the browser/markup level so much easier. |
HTML import feature is what big frameworks offer indirectly. I think, if we've this feature then we've more possibilities to write nice things in a simple way. If HTML imports will be present right into the browser then I'll feel that it is a complete framework. |
Further to @brandondees' point, I think I'd point out that offline-first PWAs using Service Worker very much encourage a client-side approach. For example in our PWA (editor.construct.net), despite it being a large and complex web app, we generate virtually nothing on the server side. This is the obvious way to design something that keeps working offline, because everything is static and local, and there's no need for a server to be reachable, especially if all the server is doing is a trivial substitution of content that could easily be done client side. So I think there are actually some significant use cases where you might want to process an include client-side, and "just do it on the server" doesn't cover everything. |
FYI, there was a same discussion happened at WICG/webcomponents#280 |
I've implemented my own very quick-and-dirty demonstration here devpunks/snuggsi#109 to begin experimenting with the pros/cons this feature might have, and we're attempting to keep track of other related efforts for reference as well. @snuggs took it beyond the most basic proof of concept and appears to have brought it close to general production-readiness. I had a discussion recently with a colleague whose initial impression was that this concept merely re-invents server-side includes, which should otherwise be easy enough to work with for most content authors, but I think there are some significant subtle differences still. It's not clear to me why server side includes have not been well leveraged in commonly used website building tools, and I think the reasons boil down to a lack of accessible (read: free) and user-friendly (enough for non tech-savvy users) authoring tools supporting that technology, and lack of standardization. There can be performance benefits from automatically leveraging client side caching of partial documents, which is something I was always baffled by the absence of since I first began learning web dev. New page loads for a given site can retrieve primarily only the portions of the document that are unique, without the need to re-transmit boilerplate sections such as header, navigation, footer, sidebars, etc. without even getting into how the same kinds of benefits also apply when using web component templates. |
Oops - sorry about closing accidentally. I had not been sure about the advantage of client-side processing against server-side include (including PHP's |
Indeed @TakayoshiKochi we created a super simple
I concur with @domenic. on providing a sound iteration/adption/developer ergonomics being worked on in this pull request. The algoritm was as simple as follows. Also works with nested dependencies due to custom elements lifecycle reactions: Element `import-html`
(class extends HTMLElement {
onconnect () {
this.innerHTML = 'Content Loading...'
this.context.location = this.getAttribute `src`
let headers = new Headers({'Accept': 'text/html'})
fetch (this.context.location, {mode: 'no-cors', headers: hdrs})
.then (response => response.text ())
.then (content => this.parse (content))
.catch (err => console.warn(err))
}
parse (string) {
let
root = (new DOMParser)
.parseFromString (string, 'text/html')
.documentElement
, html = document.importNode (root, true)
, head = html.querySelector
`head`.childNodes
, body = html.querySelector
`body`.childNodes
this.innerHTML = ''
this.append ( ... [ ... head, ... body ] )
}
}) Any caveats to Hope this helps @TakayoshiKochi /cc @brandondees |
I was thinking last days since @TakayoshiKochi opened this issue. And found really interesting how to integrate this feature include with |
Ignoring the fact that that code doesn't work, at all, you're really overthinking it. Here's a complete HTML test page. Just change the source to include. <!DOCTYPE html>
<html>
<head>
<script>
class include extends HTMLElement {
connectedCallback() {
fetch(this.getAttribute('src'), {mode: 'cors', credentials: 'same-origin'})
.then(response => response.text())
.then(text => this.outerHTML = text)
.catch(err => console.warn(err));
}
}
customElements.define('include-html', include);
</script>
</head>
<body>
<!-- Include the partial HTML. -->
<!-- If the included HTML has includes, they will be included too. -->
<include-html id="test" src="to_include.html" />
<!-- No problems here either. It just logs an error if this happens. -->
<!-- script>document.getElementById('test').remove()</script -->
</body>
</html> This should be a void element in my opinion. There's nowhere to put any nested elements except after everything, so you might as well just put them outside the include instead. p.s. "Any caveats to |
@Yay295 Nice. But how to execute scripts that are present in The concept of HTML import should be more than just pasting static HTML, right? |
I think the intent here is just to paste DOM content in to another document. HTML imports are a different feature. |
Ok @AshleyScirra . You're right. As consumer, If paste DOM content in to another document then I expect to see |
/cc @brandondees @pachonk |
I'm not. I think you missed or misunderstood the "would allow for" bit. An attribute-based solution, like I'm not saying that everyone should be doing this, but it would be possible. I'm definitely not saying new formats should be standardised as part of this effort. I'm showing that a lower-level solution is more versatile and enables more use-cases than a higher-level attribute-based solution. |
Can't these two solutions be able to live together, side-by-side? How would you include a document fragment without JavaScript, only in pure HTML? HTML does support embedded content (img, video, iframe, embed, object, etc...). The real question here is why can't you embed a document fragment in the current HTML document? You can embed a whole HTML document, with The objective is to be pure HTML, JavaScript-free. It is to easily manage the caching system to eliminate redundant data requested. It is also to easily manage the content server-side; for example, not having to modify multiple HTML documents that should have the same content written in them, like a menu for example. A client-side include is really about writing efficiently HTML documents without relying on JavaScript. A browser should be able to build an HTML document from different document fragments. It really is just a cut-and-paste process. |
Yes, like I said:
|
I don't think @jakearchibald's comment is an either/or even - if you answer/create the low level thing it would force the answers it seems you'll need for the high level thing (in fact, N potential high level things).. .I don't think that means don't simultaneously try to do the obvious high level thing, or wait until it's shipped and we have lots of things using it... At least, if there is an obvious seeming high level thing we can kind of agree on (I'm not sure it's this, but maybe?). |
I hadn't yet heard new ideas related to potentially locking an element for writing in a long time (outside of the old display locking discussions that became content-visibility). Without this new concept, I would assume that the behavior would just have to be the second option.
So I agree here that this question would need to be settled first, since we don't have either the concept of an active writer, or mid-document streaming updates, and their interaction is important. Without this idea of an active writer, I was assuming that the first option here is the way to go. Is there a place that |
Nah I was just making shit up on the spot 😄 |
We need this. Explainer and live demo: HTML Includes
If you have a static website, introducing a server just for multi-file code organization can be complete overkill for many use cases. A JavaScript based solution also requires JavaScript and is non-standard. Even CSS has HTML Includes works without JS, and being standardized would mean common support across apps, IDEs (types, intellisense), and build tools (f.e. bundlers for optimization, which @domenic will love to use instead of loading multiple HTML files). It is 100% worth having this built-into browsers. Currently (see the live demo) it looks like this: <template inlined src="./some.html"></template> but I'm starting to think <template include src="./some.html"></template> Also, it is a
By default, it is synchronous, and easy to understand. We could add an SimplicityThe mental model, at least for a first version, is very easy to understand: the HTML from separate file gets "inlined" or "included" in place exactly as if you wrote it there in the first place (and hence why the default is synchronous). This code, <!-- some.html -->
<p>hello</p> <template include src="./some.html"></template>
<p>world</p> would be practically the same is having written this: <!-- some.html -->
<p>hello</p>
<p>world</p> And that's practically the whole spec! Let's keep this as simple as possible for a first version. |
Synchronous fetching is a big no-no. That's not happening. |
IMO the <template src="xxx" tag /> |
@annevk ,
The DCE could serve not just rendering but some prep logic for other page content. It should be up to developer to define the hydration level and priority. As SCRIPT does with defer and other attributes. Another thing, the hydration scope and priorities have not beed discussed in the scope of DCE discussion yet. From my experience, I would need to hold page content DCE rendering till the moment the page level template with headers/footers are loaded. Only then it makes a sence for other DCE to be rendered. You can imagine quite a bit of such container-child scenarios. |
@sashafirsov it might just be me, but I'm unfamiliar with terms like "DCE", "hydration level", "hydration scope". They don't seem to be web platform concepts, so I'm struggling to understand your comment. |
@jakearchibald , html include is a particular case for DCE( declarative custom element ) - a proposal in baking for no-js web components development. The hydration is a pattern which is used by most of scalable apps. Virtual scrolling and server side rendering are the particular cases for that. All of mentioned are under heavy discussions in w3c. I bet you familiar as with concepts as with discussions existence. Taking your comment as sarcasm than. |
why to use blank With |
@trusktr yes, just focus on making the simplest version possible! We can already convert a stylesheet from inline to external, and a script from inline to external, so should be able to convert html from inline to external. eg <!-- index.html -->
<p>hello</p>
<html src="./world.html" />
<!-- world.html -->
<p>world</p> It would just ignore all stylesheets and scripts in the fragment. |
@annevk Sync fetching would be very bad indeed. That's not what I meant, and not what we want. Let me rephrase: The needFetching should be async, but for sanity the default execution model should be that the execution is "down the page" linearly, the same as with existing non-module Without a linear execution model by default, content will pop into the page in a random order, introducing unwanted FOUC by default, and would require JavaScript for handling the situation appropriately. Using JavaScript would defeat the purpose of the proposal. HowThe parser can continue parsing forward and fetching files in parallel (async), while the execution catches up. While fetching external files, further includes (or non-module scripts and linked styles) can be also fetched in parallel. The end goal for default behavior is that externalizing a piece of HTML would essentially behave the same as if it were written inline. The only difference would be slightly more time for the page to execute due to network requests. To the user, the only "difference", before and after assuming the same exact network speed, would be as if the connection to the website got slower by some amount (depending on the number of externalized pieces of HTML and hence the number of additional network requests). OptimizationThe above model is very easy to optimize in a way that does not require much thought: a bundler would simply inline the content (recursively, in case of includes inside includes, or other non-module scripts and linked styles), without there being a difference in the final behavior of the page apart from speed differences (no random popping/FOUC of content before optimization/bundling, same visible behavior after but faster). |
Some people have mentioned that using I would like the capability that I'd gain as an end user of the feature, but people with more experience on the browser implementation side may know what's the best approach from a technical perspective ( Do any implementers here have thoughts on the easiest implementation path? |
@bburns Wouldn't it be easier to simply run existing HTML parser logic on the included HTML without making new logic that clips out styles and scripts? Plus, then the include would not be the same as writing HTML inline. The goal is to simply put HTML in a separate file. Otherwise it would be unexpected to move HTML to a separate file and it no longer working. |
@chriscoyier coincidentally wrote about this yesterday: |
I've made a javascript implementation using I don't think my implementation is what you would build into the browser, but I do think it could be used to explore potential issues and consequences of implementint a native As for use-cases. I found it invaluable when working with micro-services. Each service gets its own UI code, on its own URL, and a container application can just include that. This can be achieved with things like web-components as well, but this feals much more web-like. If the service fails, the include isn't resolved, so there is no UI, but the other services keep working like normal. There should probably be a way to show that the include failed, just like a normal 404 page inside an iframe. |
I was assuming the reason this wasn't already a feature was due to corner cases in doing that, so... it would be nice just to be able to include static html - the main page could include the stylings and js. So you could have something simple like
instead of
which is hard to remember! I didn't even know about the 'object' tag until someone just posted it here (since deleted?). |
@bburns , yes |
If It is already possible to inline shadow DOM trees using the I wrote a website using this idea using a |
I think #2142 may be a necessary primitive for this feature. |
And |
This comment has been minimized.
This comment has been minimized.
@justinfagnani This is similar to what I had in mind when suggesting the persistent fragment proposal use a element (something which I think you suggested as well), as it could facilitate the desired behaviour of html includes (comment). Both features share common needs of allowing placement anywhere in the DOM (inside ul, table, etc), as well as the contents appearing as if they had no wrapping element with regards to CSS (child selectors work as if the contents where a child of the nearest parent element exclusive of the wrapper itself). Example: <fragment src="/content.html">
<span class="spinner"></span>
Loading...
</fragment> It would be quite nice if 2 highly requested features like this could have a unified solution. With potential of also addressing out of order streaming. <fragment src="#content"></fragment>
<!-- Later in the document -->
<template id="content">
Hello World
</template> |
Uh oh!
There was an error while loading. Please reload this page.
Spun off from HTML modules discussion
There are certain amount of interest that including HTML snippet into an HTML document, without using JavaScript. That would be similar to
<iframe>
, but more lightweight and merged into the same document.It would work as a naive way to have your header and footer sections defined in one place.
(Edit by @zcorpan: also see #3681)
The text was updated successfully, but these errors were encountered: