I’m not new to programming, but I am somewhat new to web development and I’m trying to figure out the most preferred way of taking a standalone header from one html document and adding it to other html documents without code duplication. If possible I want to do this with Javascript so I can learn with more basic tools before expanding further.

I’ve researched this a fair bit, but the advice is a bit confusing since it either seems out of date or possibly not the most secure way of handling things. Is there a preferred way of doing something like this?

  • CombatWombatEsq@lemmy.world
    link
    fedilink
    arrow-up
    7
    ·
    edit-2
    1 year ago

    p sure you’re looking for a web component. You’ll create a new component that can be used like

    <my-header></my-header>

    Then import the file with the definition of the custom web component on both pages et voilà! You’ve shared your header between pages.

    I will admit I’m a bit biased because I’m the author of a web component framework: https://tybalt.org . But! I still think that’s what you’re looking for.

  • Redkey
    link
    fedilink
    arrow-up
    6
    ·
    edit-2
    1 year ago

    After reading your responses to some other comments here, I might be able to offer some advice. I haven’t done professional web dev for a long time now, but I’ve kept my hand in a little with hobby projects.

    First, you need to imagine a wall between the server and the client (browser). Unless you deliberately build a connection between the two, it won’t exist. A standard static webserver only sends flat files to the browser. Now, if I understand what you’re thinking, what you want to do is technically possible, but it’s kind of like getting milk from the corner store by moving the store’s fridge into your kitchen.

    Usually what you’re talking about is done with dynamically served pages, using some kind of server-side scripting. The server-side script grabs all the pieces of your page from files, assembles them on the server, then sends the finished page to the user’s browser (on the other side of the “wall”) as a regular, static page. I haven’t used it myself, but I believe that Node.js allows us to use JavaScript as a server-side scripting language, although you still need to have it installed on your server (as with any server-side scripting language).

    It should certainly be possible to achieve a similar end result by sending an initial page to the client, loaded with JavaScript that performs subsequent requests from the browser back to the server, and assembles the page on the client’s side, but doing your basic page construction this way would probably be considered by most as a really messy solution.

    Here’s an article I found which may give you some tips for further research: https://css-tricks.com/the-simplest-ways-to-handle-html-includes/

    If I absolutely had to do something like this with client-side JavaScript, I’d probably make a .js file (or files) with each section (i.e. header, footer, etc.) being handled by a single function that takes a CSS DIV id and fills it from static strings with insertAdjacentHTML() calls. This is nasty enough without trying to write a script that loads and parses other HTML pages from within the browser.

    It’s easy enough to include extra .js files in an HTML file; you just need to make sure that the included files have loaded before you start trying to alter your page in the browser. Keep in mind that those “included” .js files are actually going to be fetched by the user’s browser in a separate HTTP exchange, after the inital page request, although most browsers will parse the page as if the included files were literally copied and pasted into the base HTML at the point where they are included.

    • MossBear@lemmy.worldOP
      link
      fedilink
      arrow-up
      1
      ·
      1 year ago

      That makes sense. Thanks for the well thought out explanations. I am finding that I need to adjust my assumptions about how things work on the webdev side since it seems to work a bit differently than I expected. I’m still trying to feel out what I should and shouldn’t be using for particular tasks, so posts like these are helpful.

  • Null User Object
    link
    fedilink
    arrow-up
    5
    ·
    1 year ago

    On it’s face, this is a very odd request. I feel like, in trying to simplify the question, you’ve left out a lot of pertinent details.

    My suspicion is that you have a specific problem you’re trying to solve, and, due to lack of experience with web development, you’ve settled on this solution of using JS to copy an html snippet from one document to another, when a proper solution to the actual problem is probably nothing like that. Without knowing what the original problem is and what environment the code would be running in, I’m afraid it’s going to be nearly impossible to offer any suggestions.

    • MossBear@lemmy.worldOP
      link
      fedilink
      arrow-up
      2
      ·
      1 year ago

      Like I mentioned, the problem I’m trying to solve is creating a reusable header in one html document and injecting it into another rather than copying the same code across multiple pages. Is there another way that this is typically handled?

      • silas
        link
        fedilink
        English
        arrow-up
        4
        ·
        1 year ago

        I commented on another comment of yours too, but I think the easiest ways to do this would be with web components or with PHP includes

        If you want to dive deeper, you can learn a javascript framework like Astro or Svelte which have more of a learning curve but are better at organizing larger or more powerful websites/web apps

        • MossBear@lemmy.worldOP
          link
          fedilink
          arrow-up
          2
          ·
          1 year ago

          Thanks for the recommendation! I’m not familiar with Astro or Svelte, so I’ll look into those!

      • Null User Object
        link
        fedilink
        arrow-up
        3
        ·
        edit-2
        1 year ago

        This is normally done on the server, by whatever tool is building the final html pages. If it’s just a static website (doesn’t take user input, glorified brochure), then one might use a static site generator (eg Jeckyll), each of which have their own mechanism for sharing common snippets. If building a more dynamic website with a database backend, then one would be using other tool (eg. Ruby on Rails), which would also each have their own mechanisms for sharing common snippets.

      • Tippon@lemmy.world
        link
        fedilink
        arrow-up
        2
        ·
        1 year ago

        I’m still new to this, so I might be getting things backwards, but I think I’ve recently done what you’re looking for.

        I’m making a web app for a small music festival, and was duplicating the page links on every page, and having to update them all every time something changed. I found a technique online to put the links into a header.js file, then just call the script in every new page. I did the same with the footer, and created a template for a blank page with the html that couldn’t go into the header.

        I’m not near my computer to get the site with the instructions, but my Github is here if it helps. Just bear in mind that I’m new, so might not have done it in the best way

        https://github.com/Tippon/Cwmfest-test

    • MossBear@lemmy.worldOP
      link
      fedilink
      arrow-up
      1
      ·
      1 year ago

      Yeah I was planning on learning Hugo and Jekyll after I get a bit further along with HTML, CSS and Javascript. I know those would make parts of what I’m trying to do easier, but I want to try to have a deeper understanding of what can and can’t or should and shouldn’t be done with vanilla tools. I feel like know the why behind these things will be helpful.

      • dallen
        link
        fedilink
        arrow-up
        2
        ·
        1 year ago

        Ah, I see. If you want to move around HTML using your own code, I would also think about using an XML library in your language of choice.

        Handling the HTML as a tree rather than lines of code will make the kind of operations you mention much simpler.

    • MossBear@lemmy.worldOP
      link
      fedilink
      arrow-up
      2
      ·
      edit-2
      1 year ago

      I’m not far enough along to know how to answer this. I was under the possibly mistake impression that I could create a standalone html file with reusable components, tag them by id, get those elements by id in Javascript, store them as a variable and instance those component into another html document with an ordinary javascript file by getting a place holder div id in the main html file and adding the content using the innerHTML property.

      Is that not the case?

      • silas
        link
        fedilink
        English
        arrow-up
        4
        ·
        1 year ago

        If I understand you right, the closest thing to this natively is probably web components. They have really good support across browsers now, and they would accomplish what you want without adding extra javascript to weigh your site down.

        You could also learn and use a javascript framework like Astro, Svelte, Vue, React, etc. which are all industry-standard frameworks built to break your website down into a ton of reusable components and keep things organized. I like Svelte or Astro because they feel closer to vanilla HTML/CSS/JS to me. Here’s the official interactive tutorial for Svelte if you want to mess around with it: learn.svelte.dev

        PHP does have “includes” too if you want to go that route

        • MossBear@lemmy.worldOP
          link
          fedilink
          arrow-up
          2
          ·
          1 year ago

          I was looking into Astro and Svelte and those definitely seem interesting. I’ve saved links so I can get into them more in a few weeks when I’m a bit further along with the fundamentals. Thanks!

          • jaredwhite@kbin.social
            link
            fedilink
            arrow-up
            3
            ·
            1 year ago

            Also just throwing this out there: I run a Discord called The Spicy Web that really is about learning and building stuff with the fundamentals, even for old-timers like myself (but all the more for newbies! So much advice out there is about pulling in tons of opinionated tools and dependencies, even when you don’t need them…). At any point if you want to bounce ideas or questions off folks in real-time, check it out!

            • silas
              link
              fedilink
              English
              arrow-up
              2
              ·
              1 year ago

              Thanks, I’ll take a look at this too!

            • MossBear@lemmy.worldOP
              link
              fedilink
              arrow-up
              2
              ·
              1 year ago

              Much appreciated, thanks! I’ll save a link to this and have a look! I am definitely a fan of using simple tools, so that definitely appeals to me.

          • silas
            link
            fedilink
            English
            arrow-up
            1
            ·
            1 year ago

            No problem! Svelte has an awesome Discord community, and we got a Svelte community here too. Feel free to ask me any questions as well

      • William@lemmy.world
        link
        fedilink
        arrow-up
        2
        ·
        1 year ago

        It’s technically possible to do that, but it’s kind of a pain. I asked about server-side JS because the server is where I’d do something like this as my first choice.

        If you really want to do it in the browser, you could use an AJAX call to get the html from the server, then use DOM functions to find that snippet by id. (Or just put them in separate html files and save yourself the pain of those DOM functions.)

        I found this for you. https://gomakethings.com/getting-html-with-fetch-in-vanilla-js/ I think it actually has most of what you want to do.

        • MossBear@lemmy.worldOP
          link
          fedilink
          arrow-up
          2
          ·
          1 year ago

          Thanks for the link and the advice. I wasn’t sure how to approach something like this since it’s handled a bit differently with the software development I’m used to, but I think I’m starting to get a clearer idea of why things work the way they do on the web side.

  • MrPoopyButthole@lemmy.world
    link
    fedilink
    English
    arrow-up
    2
    ·
    1 year ago

    You’re trying to reinvent the wheel. This has been solved by modern JS frameworks. Learning one of them will get you a safer better site than trying to “Frankenstein” your own with little experience.

    • jaredwhite@kbin.social
      link
      fedilink
      arrow-up
      3
      ·
      1 year ago

      I disagree. The fundamentals of the web specs are more important than ever, and many projects don’t even need a frontend framework.

  • MossBear@lemmy.worldOP
    link
    fedilink
    arrow-up
    2
    ·
    1 year ago

    I just told my wife how impressed I am to have gotten so many helpful responses. You all are great!