I'm trying to convert my personal notes to HTML and keep them modularized. I'm trying to get this test code to work.
I have a file called called main-file.html.
I have another file called sub-file.html. The only code within this file is "Hello World".
I want to double click on the main-file.html such that when it opens up in my web browser, I see a page with the words "Hello World" on it, because the main-file.html is reading the code from sub-file.html and rendering it, as though that code were within main-file.html itself. Eventually, I want to reference numerous subfiles.
What is the simplest code that will achieve this result? Using JavaScript is acceptable. I do not want to use 3rd party software, PHP, SSI, web servers, etc. because I want this to work on any computer out of the box with just a web browser. I also don't want to use iFrames or objects, because I've tried for days to get this to work for my application and I can't get it to render properly without lots of awkward scrollbars, etc. (unless you know of a way to render each sub-file one after the other without scrollbars, which I couldn't figure out). I just want the main-file.html to read the code within sub-file.html and treat it as though sub-file.html's code was within main-file.html.
I've been working for days with Google Bard and ChatGPT trying to get this to work, with no success. Any help is very much appreciated.
I tried this code, with no success.
<!DOCTYPE html>
<html>
<head>
<title>Main File</title>
</head>
<body>
<div id="content"></div>
<script>
// Use JavaScript to load and display content from sub-file.html
fetch('sub-file.html')
.then(response => response.text())
.then(data => {
document.getElementById('content').innerHTML = data;
})
.catch(error => {
console.error('Error loading sub-file.html:', error);
});
</script>
</body>
</html>
CodePudding user response:
You can do that without JavaScript using iframe
to load your subpage
<!DOCTYPE html>
<html>
<head>
<title>Main File</title>
</head>
<body>
<iframe id="content" src="sub-file.html" width="100%" height="300">
</body>
</html>
The only limit is that you have to set a specific height, if the content of the subpage is longer it will appear in the scrollbar.
The reason you can't use JavaScript to do this is for the CORS (Cross-origin resource sharing) policy that prevents you to call directly a file.
CodePudding user response:
Your code will work only if you execute it into a web server. If you execute it in a web browser like a file, it will gives you an exception.
Personally I put my HTML notes in single files.