<html>
<body>
<h1>Put your HTML content before insertion of b.js.</h1>
...
<script src="b.js"></script>
...
<p>And whatever content you want afterwards.</p>
</body>
</html>
b.js:
document.write('\
\
<h1>Add your HTML code here</h1>\
\
<p>Notice however, that you have to escape LF's with a '\', just like\
demonstrated in this code listing.\
</p>\
\
');
document.write(`
<h1>Add your HTML code here</h1>
<p>Notice, you do not have to escape LF's with a '\',
like demonstrated in the above code listing.
</p>
`);
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/application/html; charset=iso-8859-1">
<meta name="Author" content="me">
<meta copyright="Copyright" content= "(C) 2013-present by me" />
<title>Menu</title>
<script type="text/javascript">
<!--
var F000, F001, F002, F003, F004, F005, F006, F007, F008, F009,
F010, F011, F012, F013, F014, F015, F016, F017, F018, F019;
var dat = new Array();
var form, script, write, str, tmp, dtno, indx, unde;
/*
The "F000" and similar variables need to exist/be-declared.
Each one will be associated with a different menu item,
so decide on how many items maximum you are likely to need,
when constructing that listing of them. Here, there are 20.
*/
function initialize()
{ window.name="Menu";
form = document.getElementById('MENU');
for(indx=0; indx<20; indx++)
{ str = "00" + indx;
tmp = str.length - 3;
str = str.substr(tmp);
script = document.createElement('script');
script.type = 'text/javascript';
script.src = str + ".js";
form.appendChild(script);
}
/*
The for() loop constructs some <script> objects
and associates each one with a different simple file name,
starting with "000.js" and, here, going up to "019.js".
It won't matter which of those files exist or not.
However, for each menu item you want to display on this
page, you will need to ensure that its .js file does exist.
The short function below (inside HTML comment-block) is,
generically, what the content of each one of the .js files looks like:
<!--
function F000()
{ return ["Menu Item Name", "./URLofFile.htm", "Description string"];
}
-->
(Continuing the remarks in the main menu.htm file)
It happens that each call of the form.appendChild() function
will cause the specified .js script-file to be loaded at that time.
However, it takes a bit of time for the JavaScript in the file
to be fully integrated into the web page, so one thing that I tried,
but it didn't work, was to write an "onload" event handler.
The handler was apparently being called before the just-loaded
JavaScript had actually become accessible.
Note that the name of the function in the .js file is the same as one
of the pre-defined variables like "F000". When I tried to access
that function without declaring the variable, attempting to use an
"onload" event handler, the JavaScript debugger claimed that the item
was "not available". This is not something that can be tested-for!
However, "undefined" IS something that CAN be tested-for. Simply
declaring them to exist automatically makes all of them "undefined".
When the system finishes integrating a just-loaded .js script file,
the appropriate variable, like "F000", will become something other
than "undefined". Thus it doesn't matter which .js files exist or
not, because we can simply test all the "F000"-type variables, and
ignore the ones that are "undefined". More on that later.
The line below specifies a delay of 2 seconds, before any attempt
is made to access the scripts that were loaded. That DOES give the
system enough time to fully integrate them into the web page.
(If you have a really long list of menu items, or expect the page
to be loaded by an old/slow computer, a longer delay may be needed.)
*/
window.setTimeout("BuildMenu();", 2000);
return;
}
//So here is the function that gets called after the 2-second delay
function BuildMenu()
{ dtno = 0; //index-counter for the "dat" array
for(indx=0; indx<20; indx++)
{ str = "00" + indx;
tmp = str.length - 3;
str = "F" + str.substr(tmp);
tmp = eval(str);
if(tmp != unde) // "unde" is deliberately undefined, for this test
dat[dtno++] = eval(str + "()");
}
/*
The loop above simply tests each one of the "F000"-type variables, to
see if it is "undefined" or not. Any actually-defined variable holds
a short function (from the ".js" script-file as previously indicated).
We call the function to get some data for one menu item, and put that
data into an array named "dat".
Below, the array is sorted alphabetically (the default), and the
"dtno" variable lets us know exactly how many menu items we will
be working with. The loop that follows creates some "<span>" tags,
and the the "innerHTML" property of each one is set to become an
"anchor" or "<a>" tag, for a link to some other web page. A description
and a "<br />" tag gets included for each link. Finally, each new
<span> object is appended to the menu-page's "form" object, and thereby
ends up being inserted into the middle of the overall text on the page.
(For finer control of where you want to put text in a page, consider
placing something like this in the web page at an appropriate place,
as preparation:
<div id="InsertHere"></div>
You could then use document.getElementById("InsertHere") to get it into
a variable, for appending of <span> elements, the way a variable named
"form" was used in this example menu page.
Note: You don't have to specify the link in the same way I did
(the type of link specified here only works if JavaScript is enabled).
You are free to use the more-standard "<a>" tag with the "href"
property defined, if you wish. But whichever way you go,
you need to make sure that any pages being linked actually exist!
*/
dat.sort();
for(indx=0; indx<dtno; indx++)
{ write = document.createElement('span');
write.innerHTML = "<a onclick=\"window.open('" + dat[indx][1] +
"', 'Menu');\" style=\"color:#0000ff;" +
"text-decoration:underline;cursor:pointer;\">" +
dat[indx][0] + "</a> " + dat[indx][2] + "<br />";
form.appendChild(write);
}
return;
}
// -->
</script>
</head>
<body onload="initialize();" style="background-color:#a0a0a0; color:#000000;
font-family:sans-serif; font-size:11pt;">
<h2>
MENU
<noscript><br /><span style="color:#ff0000;">
Links here only work if<br />
your browser's JavaScript<br />
support is enabled.</span><br /></noscript></h2>
These are the menu items you currently have available:<br />
<br />
<form id="MENU" action="" onsubmit="return false;">
<!-- Yes, the <form> object starts out completely empty -->
</form>
Click any link, and enjoy it as much as you like.<br />
Then use your browser's BACK button to return to this Menu,<br />
so you can click a different link for a different thing.<br />
<br />
<br />
<small>This file (web page) Copyright (c) 2013-present by me</small>
</body>
</html>
var link = document.createElement('link');
if('import' in link){
//Run import code
link.setAttribute('rel','import');
link.setAttribute('href',importPath);
document.getElementsByTagName('head')[0].appendChild(link);
//Create a phantom element to append the import document text to
link = document.querySelector('link[rel="import"]');
var docText = document.createElement('div');
docText.innerHTML = link.import;
element.appendChild(docText.cloneNode(true));
} else {
//Imports aren't supported, so call polyfill
importPolyfill(importPath);
}
let nick = "Castor", name = "Moon", nuts = 1
more.innerHTML = `
<h1>Hello ${nick} ${name}!</h1>
You collected ${nuts} nuts so far!
<hr>
Double it and get ${nuts + nuts} nuts!!
`
<div id="more"></div>
This way we can include html without encoding quotes, include variables from the DOM, and so on.
It is a powerful templating engine, we can use separate js files and use events to load the content in place, or even separate everything in chunks and call on demand:
let inject = document.createElement('script');
inject.src= '//....com/template/panel45.js';
more.appendChild(inject);
<!-- all-css.html -->
<meta data-include-html="bootstrap-css.html">
<meta data-include-html="fontawesome-css.html">
<!--
If you want to use w3.js.include, you should change as below
<meta w3-include-html="partials/head/bootstrap-css.html">
<meta w3-include-html="partials/head/fontawesome-css.html">
Of course, you can add the above in the ``popup.html`` directly.
If you don't want to, then consider using my scripts.
-->
<!-- hello-world.html -->
<h2>Hello World</h2>
脚本
// include.js
const INCLUDE_TAG_NAME = `data-include-html`
/**
* @param {Element} node
* @param {Function} cb callback
* */
export async function includeHTML(node, {
cb = undefined
}) {
const nodeArray = node === undefined ?
document.querySelectorAll(`[${INCLUDE_TAG_NAME}]`) :
node.querySelectorAll(`[${INCLUDE_TAG_NAME}]`)
if (nodeArray === null) {
return
}
for (const node of nodeArray) {
const filePath = node.getAttribute(`${INCLUDE_TAG_NAME}`)
if (filePath === undefined) {
return
}
await new Promise(resolve => {
fetch(filePath
).then(async response => {
const text = await response.text()
if (!response.ok) {
throw Error(`${response.statusText} (${response.status}) | ${text} `)
}
node.innerHTML = text
const rootPath = filePath.split("/").slice(0, -1)
node.querySelectorAll(`[${INCLUDE_TAG_NAME}]`).forEach(elem=>{
const relativePath = elem.getAttribute(`${INCLUDE_TAG_NAME}`) // not support ".."
if(relativePath.startsWith('/')) { // begin with site root.
return
}
elem.setAttribute(`${INCLUDE_TAG_NAME}`, [...rootPath, relativePath].join("/"))
})
node.removeAttribute(`${INCLUDE_TAG_NAME}`)
await includeHTML(node, {cb})
node.replaceWith(...node.childNodes) // https://stackoverflow.com/a/45657273/9935654
resolve()
}
).catch(err => {
node.innerHTML = `${err.message}`
resolve()
})
})
}
if (cb) {
cb()
}
}
// popup.js
import * as include from "include.js"
window.onload = async () => {
await include.includeHTML(undefined, {})
// ...
}