0

My website uses this in the frame.html head so it appears globally:

<!--START: infopages-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
$(document).ready(function(){

   $('#15').load("../assets/15.html");
   $('#16').load("../assets/16.html");
   $('#17').load("../assets/17.html");
   $('#18').load("../assets/18.html");
   $('#19').load("../assets/19.html");
   $('#20').load("../assets/20.html");

});
</script>
<!--END: infopages-->

Other individual pages/places will have a reference like this (different pages make use of different ids):

<div id="19"></div>

So the content from those numbered HTML pages load where the div appears.

BUT ...I was told I should no longer use jQuery and instead I should use querySelector and modules. The problem is I am not at all familiar with that. Can someone please help me with how I should code the above using querySelector & modules? Or is there a better way?

I tried to educate myself on how this should work but not finding good examples on the web. Seems like this should be fairly straight forward?

2
  • Do the HTML files you're loading contain any JavaScript? jQuery will execute the JS, emulating that in vanilla JS is complicated. Commented Sep 13, 2024 at 22:29
  • I don't see how modules are relevant to this. Commented Sep 13, 2024 at 22:30

2 Answers 2

0

I'm not aware of any vanilla JS function that loads a URL into an element like that, but you can easily implement it yourself with fetch and getElementById.

<div id="19"></div>

<script>
async function loadInto(id, url) {
    let response = await fetch(url);
    if (!response.ok) throw new Error("request failed with status " + response.status);
    let body = await response.text();
    document.getElementById(id).innerHTML = body;
}

// Usage:
loadInto("19", "a.html")
</script>

Note that this assumes the .html files are fragments/elements, not full HTML files.

Sign up to request clarification or add additional context in comments.

11 Comments

... and I'd repeat the loadIinto portion for each tag and html fragment?
@StuffThings yes, you can repeat loadInto("other-id", "other.html") as many times as needed, even in a new script block.
OK. Thanks. If I am repeating that, is it somehow loading all the different html files in the background when it sees the script portion? Or it only loads the actual html when it sees the div id= portion?
@StuffThings Yes, it loads in the background all together (up to 6 at the same time, due to browser limitations). This is because it's an async function. If you want to wait for one (or all) to finish loading, you'll need await, but that's a topic for another question.
If I wanted to make more than 6 available (but only use 3 or 4 per page) .... I'd need to do something else? What I mean is, lets say I have 20 different html files I want to be able to pull from, but the pages that pull these would only pull 3 or 4 at once... then this would not work?
|
0

You can replace jQuery load with this function in a file named e.g. htmlLoader.js:

export async function loadHTML(selector, file) {
  try {
    const response = await fetch(`../assets/${file}`);
    if (!response.ok) throw new Error('Failed to read file ' + file);
    const content = await response.text();
    document.querySelector(selector).innerHTML = content;
  } catch (error) {
    console.error('Error loading the HTML file:', error);
  }
}

And then use it like this:

<div id="p15"></div>
<div id="p16"></div>
<div id="p17"></div>
<div id="p18"></div>
<div id="p19"></div>
<div id="p20"></div>

<script type="module">
  import { loadHTML } from './htmlLoader.js';

  document.addEventListener("DOMContentLoaded", () => {
    loadHTML('#p15', '15.html');
    loadHTML('#p16', '16.html');
    loadHTML('#p17', '17.html');
    loadHTML('#p18', '18.html');
    loadHTML('#p19', '19.html');
    loadHTML('#p20', '20.html');
  });
</script>

I tried it and it works.

Notes:

  1. The JS part that wants to do import has to use type="module".
  2. I had to change the IDs because querySelector does not accept '#15'.
    An alternative might be to use getElementById() instead (without the #).

5 Comments

Since HTML5 it's legal for an ID to start with a number.
Using numbers I got the error Uncaught SyntaxError: Failed to execute 'querySelector' on 'Document': '#15' is not a valid selector. Maybe caused by my barebones HTML but still.
That's a restriction on CSS selectors, not HTML. stackoverflow.com/questions/20306204/…
So they are still to be avoided but for another reason. Who makes up such inconsistent rules...
It's probably because CSS selectors have to be parsed. You can use . in an ID, but the CSS selector #foo.bar will treat .bar as a class selector.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.