(评论)
(comments)

原始链接: https://news.ycombinator.com/item?id=41070709

HTML 缺乏轻松合并外部 HTML 文件或 SVG 图形的能力,而不会因缓存和加载时间差而导致性能问题。 为了解决这个问题,您可以创建“包含”,其中 HTML 文件的某些部分在渲染时被替换为单独文件中的内容。 此方法改进了缓存,并允许更简单地管理大型网站中的重复元素。 使用“包含”可以动态插入内容,例如用户偏好、评论或基于特定条件的附加数据。 这项技术增强了网页设计的灵活性,并为复杂的网站提供了各种好处。 使用“包含”的一个显着优点是提高了跨多个页面的缓存能力,从而加快了加载时间并提高了网站的整体性能。 通过对关键数据部分实施“包含”功能,开发人员可以提高编码实践的效率,减少花在冗余任务上的时间。 此外,利用“包含”的做法简化了将现有 HTML 文档转换为单一结构化框架的过程。 如果使用得当,该策略可以帮助简化大型网站的维护和开发流程。 在需要集成第三方资源或非标准格式的情况下,Tidy-HTML5 等工具可能会很有帮助。 这些工具使用户能够将 XML 处理应用于导入的网页内容,为进一步定制和优化提供增强的功能。 最终,选择以 XML 为中心的方法在前端开发方面比传统 HTML 具有优势,可以直接操作域模型。 利用 XSLT 转换有助于将原始数据无缝转换为精美的 HTML 显示,使设计人员和开发人员能够以最小的开销生成复杂的 Web 应用程序。 理想的场景是 API 端点和网页共享共同点,允许通过优化的模板化界面直接访问和显示基本信息。 操作模板和调整可视化组件可以反映对 CSS 属性的简单更改,让新手程序员可以轻松愉快地进行实验。 虽然 SVG 因其无损缩放和一致的外观而颇具吸引力,但在游戏或专业项目中广泛使用的实用性仍然值得怀疑。 出现的问题涉及嵌入文本和图形的可扩展性和易读性,需要频繁的微调和潜在的特定于平台的解决方案。 因此,建议的图像最大比例

相关文章

原文


Isn't the fundamental issue here not so much anything to do with ``, but with the fact that you can't easily include HTML snippets from other files in HTML? Like, the only reason not use the tag seems to be "it's not cached, and it contains a BUNCH of svg, and it has to be loaded with the main HTML page"

Can't you say that about anything in HTML? Like, imagine you had a huge `` tag that contained a bunch of stuff, but it's essentially the same (except for, like, the title) for all documents. Don't you wanna do this?

    
    
      <<< include head.html >>>
      Cool page!
    
    
        
            <<< include logo.svg >>>
        
    
    

Where the `>>` is a pretend bit of HTML that makes the browser fetch that from somewhere else. A preprocessor, more or less.

I realize this is what templating languages are for, but if this happened on the HTML layer, the browser could do way better caching.



To me at least this feels like a fairly natural addition to HTML. You can already pull in external scripts, stylesheets, images, video, etc, so why not page partials too? A sibling comment mentions XSLT which is cool, but nobody knows about it because it doesn’t follow any patterns set in HTML and HTML doesn’t have any breadcrumbs that might lead someone to discover XSLT. Something like flows with expectations much better.

Something I find a bit funny now is that for the longest time back in the 2000s, nearly the entirety of my usage of PHP was comprised of PHP includes to make up for this gap in HTML functionality (I had no idea XSLT existed then).



It had breadcrumbs back in 2004 (e.g. those neat "valid XHTML 1.1" badges from W3C back when badges on your website were cool, and e.g. W3 Schools actually put it above javascript[0]. XHTML was supposed to be the next big thing). These days it seems that browser vendors just don't like it for whatever reason (tinfoil hat on: because almost all of them benefit from javascript-based spyware, and so prefer a world where even static pages require javascript to be enabled to show anything), and so documentation acts like it is some legacy thing instead of what it is: a perfect fit for the 99% of websites that need some templates and don't have much dynamic interaction.

Other cool web tech that should have "won": XForms[1]. Imagine if HTML forms had things like declarative data-binding (with XPath expressions! Imagine jq built directly into the browser 20 years ago and usable by forms) and types/constraints/validation built right in. This would be 1000x more useful for your average web dev than something like USB or GPU support or Wasm. You'd be able to make complex interactive forms in much the same way that you do a spreadsheet.

[0] https://web.archive.org/web/20040727061732/http://www.w3scho...

[1] https://www.youtube.com/watch?v=2yYY7GJAbOo



One reason that this is slightly more complicated than it appears is that you have to decide what ignore when doing the inclusion. Including an image will not override anything specified in the "parent" HTML, but including HTML might result in conflicts. Who wins, who loses, etc. etc.



Why isn't it exactly the same as if the doc had the includes filled out and then processed semantically, much like C?

All <<>> could be replaced with contents first. Then it's just a page of html as now.



HTML does have a preprocessor. It's called XSLT, and it has includes, though they have no deferred fetch. Also, being a preprocessor, you can't interact with it after page load (unless you use a javascript implementation). It's been built into browsers for 20+ years. Still works great, but browsers never supported versions past 1.0 so it shows its age some.



> though they have no deferred fetch

Also, at least back when we excised the last bits of it from our old codebase, no useful caching of either stylesheets or included resources (other stylesheets), so if you tried to mix client-side processing with HTTPS you were in for quite some pain unless you had a fast, very low latency, uncongested, link.



Currently it looks like at least Firefox and Chromium both cache stylesheets and included files as you'd expect. In fact, you can use this to increase cacheability in general. e.g. when this site is having performance issues, it often works logged out/when serving static versions of pages. It's easy to make every page static by including a `/myuser.xml` document in the xsl template and using that to get the current logged in user/preferences to put on the page. This can then be private cached and the pages themselves can be public cached. You can likewise include an `/item-details.xml?id=xxxx` that could provide data for the page to add the logged in user's comment scores, votes, etc. If the included document fails to fetch, it falls back to being empty, and you get the static page (you could detect this and show a message).



XSLT 3.0 can be directed to output HTML5 [0]. However, browsers only implement XSLT 1.0, and as far as I am aware there is no open-source XSLT 3.0 implementation.

Still, it's possible with XSLT 1.0 to produce documents in the common subset of XML and HTML5 ("XHTML5"). It can't produce the usual at the top of the document, but it can produce the alternative .

On the input side, every XSLT version only accepts valid XML, as far as I am aware.

[0] https://www.w3.org/TR/xslt-xquery-serialization-30/#html-out...



`xsltproc --html` is an example of HTML input (probably HTML4 parsing rules though?) if you really need it. This is an XSLT 1.0 processor, wrapping libxslt which most browsers use.

As for output, the difference is largely irrelevant for browser purposes since they just want a tree.

I'm not sure how many extensions the browsers allow, but a major part of the reason XSLT 2/3 failed to take off is because libxslt already provides most of the useful features from newer versions as extensions (many via EXSLT-namespaced modules, at least partially supported in browsers - see MDN); what it doesn't do is implement the unnecessary complexity that the Java world loves.



We were going to move on to XHTML after HTML4, for those variants (did it go beyond XHTML1.1?) HTML is XML compliant. That got caught in slow design-by-committee hell though so HTML5 became the defacto standard instead. There is XHTML5 which is an attempt to direct that back towards compliance, but I've never seen it used in the wild.



As far as I know, HTML5 has diverged from its origins enough that it's neither SGML nor XML. However, given the existence of XHTML5, it might be possible to parse an HTML5 DOM and re-serialize it as XHTML5, and thus it might be possible to take parseable HTML as input to XSLT, albeit with some indirection.



As I understand XSLT, it takes an XML document as input and an XML document describing the transformation, and produces an XML document as output.

But most HTML in the wild today is not valid XML. There is XHTML as mentioned by a sibling comment but it's rarely used. So if you were to start with an existing base of HTML documents, you couldn't easily add XSLT preprocessing to them. The issue is with the input rather than the output.



If you're using it as a template language for your own pages, you can of course just write it correctly (this is not different than needing to use correct syntax for react code to compile).

If you have someone else's documents, or need to mass convert your own to fix them, there's HTML tidy[0]. This one is quite useful to be able to run XML processing CLI tools on scraped web pages.

But the real power is in delivering XML to the client, not HTML. This lets you work in the domain model directly on the frontend, and use XSLT to transform that into HTML for display. So of course you'd use well-formed XML in that case.

Imagine if you didn't have a distinction between APIs and pages; you just returned the data along with a link to a template that says how to display it and (ideally) a link to a schema definition. Modifying templates for components could be as easy as modifying CSS attributes in the browser console, giving the next generation an easy way to peak and play around with how it all works as they're growing up. We were so close, and then things veered off into the hellworld that is the modern web.

[0] https://github.com/htacg/tidy-html5



HTML was invented as an SGML vocabulary, and SGML does have those inclusion mechanisms (called entities), though browsers basically never implemented those. To this date, self-acclaimed web folks ridicule XML (a simplified subset of SGML originalky invented as the base for additional vocabularies on the web, of which SVG and MathMl made it) for daring to incorporate something as basic as text variables/entities ie the "billion laughs atrack" (SGML could already limit the recursive entity expansion depth).



I think whether or not this makes sense on the client-side is up for debate.

Alternatively, though, SVGs in ```` elements could just, yknow, retain their stylability. (is there a reason they don't? this has been a long-running frustration of mine)



Yes, I want this and it would solve quite a few issues - particularly lazy loading and SPA-style content swapping could be done with better performance, because html can be easily processed and rendered during download by the browser (unlike the classic AJAX -> Json.parse -> render pipeline, which requires each step to be completed before the next one starts). Lazy loading would also not require JavaScript.



I may be completely off and/or misremembering, but isn't this what was meant to be able to do/support? Seems that this could be done by convincing Apple/Google/Firefox to reframe/update how the object element works in modern browsers.



I like to use sprite files for conditional styling of icons, because using separate file for each state creates a visible delay on state changes, which doesn't look great.

You can make them with and tags pretty easily if you understand svg a bit. I usually bundle two-state icon into a single svg file, and then use `object-position: left/right` property on the tag to switch between the variants. You can also combine this with some simple css animations.



Oh man, you're right, I didn't realize they worked this way. This basically means there is no compromise at all, I'm going to update the post. Thanks!



Well, there's still a compromise to be fair. It's defintely more work to manage these sprites and it's especially annoying when there's more than one state. I think it's possible to write some tool to automate it, but I haven't found one.



There are preprocessors that will do this. Conceptually, we would:
  include sprite-1.snippet
  include sprite-2.snippet
and it would write the defs into the page. Then later in the page, `` the defs you included.


Boxy SVG editor comes with built-in support for creation and editing of SVG icon sprites.

You can play with a sample SVG sprite on https://boxy-svg.com/#demo-symbols. Individual icons are shown under "Defs Panel -> Symbols". To edit an icon just double-click its thumbnail. To make part of an icon recolorable, select that part and then click "Fill Panel -> Paint -> Type -> Inherit".

You could then create separate symbols which contain a recolored instance of the original symbol. The underlying markup will look something like this:

  
  
    
      
        
      
      
        
      
      
        
      
    
  
Finally, use a fragment identifier to show a specific icon in HTML:
   


hmm, I didn't know you can use fragment identifiers in src attribute, that changes the game quite a bit. I remember looking for stuff like that, though. Not sure why I didn't anything, because it seems like it's been supported for quite a while. I only found the reuse inside svg in the same parent html document.



Fragment identifiers in "src" attribute seem to be supported by all modern browsers, but now I realized my example was wrong - you can reference elements, but not elements directly.

To make it work you would have to either replace with or add views to the sprite file:

  
  
    
      
        
      
      
      
    

    
    
  


It's something like this (I just quickly took this from my project, not sure if it works in this form now). This one uses the defs/use trick to reuse a path, but you can also just put two different svgs next to each other and not use the defs/use at all.

The icon:

  
  
  
    
      
      
    
  
    
    
  
    
    
  
  
HTML:
    
  
  
CSS:
  .hover-icon {
    /* make sure that only first block of the image is visible */
    object-fit: cover;
    object-position: left;
  }
  .hover-icon:hover {
    object-position: right;
  }


Yes, I do that, too. The benefit of using the sprite system is that it's pretty general, so once you have some CSS for it, it's easy to keep adding new icons. CSS filters are usually more special for each case, but I use them too (mostly for brightness and greyscale things that are repeated on multiple places, e.g. tabs or disabled state).



Another option would be to including SVG files from SVG elements, though the whole thing is a bit cursed. I'm not 100% sure how it plays with CSS and caching

Example: svg poster - includes svg diagrams - that include svg maps (maps are generated programmatically)

https://kxygk.github.io/imergination/

Though.. if you open the SVG itself (in a separate window/tab) most elements refuse to display for "security"

https://raw.githubusercontent.com/wiki/kxygk/imergination/ag...

It's honestly an unreliable format for anything that's mildly complex.. this poster will render differently in different browsers (and inkscape) and can't be turned into a PDF consistently. It's a mess



Actually, for interactivity you don't have to use CSS but can also use SMIL animations to set SVG (or CSS) properties for things like clicking/hovering, timed transitions, and even animation sequences. Never understood the CSS march of progress narrative when CSS just piecemeally incorporares concepts (paint servers, filters, etc) SVG had for 20 years now, and what's so great about having those available in CSS" wild unchecked syntax, especially when you'd need (or prefer) JS anyway. SVG at least can be targetted as a reasonable output format by vector drawing tools.



Ohh, interesting, I have never heard of SMIL. For this post I was thinking mostly of static styling (... and got a little carried way with interactive stuff in the diagram...) but I'll have to look into SMIL in the future.



There's an important caveat with this: It does not work cross-origin, and there is no way to make it work except for including some JS like svg4everybody. CORS does not apply.



I’m not confident of what is meant by “stylable”, but I’m pretty sure it’s a misnomer.

If you mean applying static styles, you can do that with any form of SVG (that is, qualifies as well).

If you mean inheriting styles from the parent document, you can only do that with inline SVG (that is,