How to separate html text file into multiple files? - html

Very basic question about html.
Because the <body> is too long, I want to divide the file into multiple files. It is not about using iframe etc, but just want to include multiple text files to create <body> of the html file.
Thank you!

You can do it using jQuery:
<head>
<script src="jquery.js"></script>
<script>
$(function(){
$("#ContentToInclude").load("b.txt or b.html");
});
</script>
</head>
And load it in HTML:
<body>
<div id="ContentToInclude"></div>
</body>

Just change the extension to .php instead of .html. Then you can just put, for example, your whole head inside the file head.php( or head.inc).
The whole thing would look something like this then:
<!DOCTYPE html>
<?php
include 'head.php';
?>
<body>
<!-- stuff in here -->
</body>
<html>
You can obviously split your body up into seperate pieces like this:
<body>
<?php
include 'firstPart.php';
?>
<!-- some other stuff -->
</body>

You can easily break your code in multiple files, Then create one file with .php extension and include them all!

With only HTML it would not be possible you need to add some JavaScript to be able to do so.
Using a data attribute with the Fetch API and some async functions you could do it as follow:
HTML file:
<div data-src="./PATH/filename.html"></div>
This element will receive as HTML content the content of the file specified in its data-src attribute.
Now the JavaScript:
async function getFileContentAsText(file) {
const response = await fetch(file);
const fileContent = await response.text();
return fileContent;
}
async function insertContentsFromFiles() {
const tbl = document.querySelectorAll('[data-src]'); // get elements with the data attribute "data-src"
for (var i=0; i < tbl.length; i++) // loop over the elements contained in tbl
tbl[i].innerHTML = await getFileContentAsText(tbl[i].dataset.src);
}
// dont forget to call the function to insert the files content into the elements
insertContentsFromFiles();
When the insertContentsFromFiles() method will be called it will first retrieve all the elements that have the data attribute data-src then we loop over these elements using their data-src value with the getFileContentAsText() method to affect their innerHTML property as the content of the file specified in the data attribute.
As we are using querySelectorAll() to get the elements with the data-src attribute the above JavaScript code will work for an unlimited amount of elements as long as they have that data attribute.
Note: In its current state the above JavaScript code is not optimized for loading a big amount of files as it process the files to be loaded one by one. If you are interested in solving this issue you may want to use promise.all() and update the insertContentsFromFiles() method to parallelize the files loading by taking advantage of the asynchronous operations.
Warning: If you plan to use elements that are in the loaded files from JavaScript you will have to retrieve them after they have been loaded into the page otherwise they will have an undefined value. To do so you can dispatch an event when a file has been loaded so you can attach specific functionnalities to the page based on the triggered events.

Related

Avoid html form classic behaviour with ajax [duplicate]

I noticed that the <script src="..."></script> tag does not allow you to use JavaScript within it, such as:
<script src="myFile.js">
alert( "This is a test" );
</script>
And this does not work, nor does it throw an error in FireBug, why is this happening, why do we have to add extra <script> tags to allow for JS to be used on the form itself?
Example
I have a file, found # script/addScript.js from my root, and this contains:
function addScript( $src )
{
var script = document.createElement( 'script' );
script.type = "text/javascript";
script.src = $src;
document.getElementsByTagName( 'head' )[0].appendChild( script );
}
This is designed to allow me to add scripts to the DOM quickly and effectively, so I tried to do this:
<script src="script/addScript.js">
addScript( "script/obj.js" );
addScript( "script/home/login.js" );
</script>
But it did not work, so I have to do this instead:
<script>
addScript( "script/obj.js" );
addScript( "script/home/login.js" );
</script>
A script element loads a single script.
It can do that from either a URL or from inline, but it still loads one script; it can't use both types of source at the same time.
If you try to include both, the inline script will be ignored:
<script src="example.js">
this_is_ignored();
</script>
… so you need multiple script elements.
<script src="example.js">
</script>
<script>
this_is_NOT_ignored();
</script>
It is worth noting that the content of the script element will still exist in the DOM, so some people use it to store data in it which the JS referenced by the src will read. data-* attributes are (arguably) a cleaner approach to that though.
Each <script> element contains one piece of executable javascript code. If you use a src attribute to load an external file, that is the piece of executable js for that element, otherwise it is the code placed between the <script></script> tags. If you try to do both, then you're attempting to associate two pieces of executable code to one script element and that is not the behavior of the script element so the browser's javascript engine ignores the inline code and executes the included file code.
As to why this is the case, it was likely a design choice by whoever established this standard. By creating a one-to-one relationship between code pieces and <javascript> elements there is no ambiguity about what code is being run or its priority.
Therefore in your case you will first have to load your external file...
<script src="script/addScript.js"></script>
and then call any functions provided by it.
<script>
addScript( "script/obj.js" );
addScript( "script/home/login.js" );
</script>
For reference, this is generally how all javascript libraries are loaded within a webpage.

Update html file content

I worked on a little startpage for my browser. Now I would like to make some changes to it, so it updates the index.html file depending on a text file, when this got changed. What whould be an efficiant way to solve this problem?
My approach would be to create a text file and read line by line from it and update the html file. In the text file I would store the links shown on my startpage - I thought maybe something like this:
|cat_media
https://mailbox.org,mail
https://netflix.com,netflix
...
http://crunchyroll.com,crunchy
https://jott-uh-be.bandcamp.com,bc
|cat_social
https://pr0gramm.com,pr0
https://stackoverflow.com,stackoverflow
https://twitter.com,twitter
https://instagram.com,insta
When the line starts with the symbol |, it creates a new <div> with the class category and the string in that line (e.G. class= 'category cat_media'). Otherwise, if the line starts with http, it will add a href-link (e.G. <a href='https://mailbox.org'>mail</a>) to the html-code.
I got this website hosted on my raspberry pi with nginx and uploaded it to my github pages.
You don't have to update the index.html file.
You can create dynamic content.
You can use PHP:
You can learn it here:
https://www.w3schools.com/php/default.asp
And here is how to read a file
http://php.net/manual/en/function.fread.php
Or if you cant use PHP you can use Javascript:
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
$(() => {
$.ajax({
url:'your-config-file.xt',
success: function (data){
console.log(data); //this is the config file. just for loop it and modify the dom
}
});
});
</script>
But your config file must contains the string how the links should be shown.
For example:
|catergory one
yt: https://www.youtube.com

Read the contents of a link or script tag using src/href

How can I read the contents of a file using
<link href='path/to/file'/>
I understand that if one adds the attribute type="text/css" then they can be read using document.styleSheets but I have a hard time figuring out how to get the content of that element though.
I understand that lesscss.js lib uses the without an ajax get call.
From: http://lesscss.org/#using-less
<link rel="stylesheet/less" type="text/css" href="styles.less" />
<script src="less.js" type="text/javascript"></script>
I need to include some templates into the page, and the sooner they are loaded the better, ( vs doing it after jquery and js has loaded)
Thanks!
I understand what you mean with before jquery. But what do you mean with "before js".
When you load less.js (which does NOT depend on jQuery) the browser runs less.js before jquery has been initialized. Notice that less.js requires JavaScript.
You can read the content of such a file leveraging a XMLHttpRequest. A basis example which shows you how to do this can be found at: How to show the compiled css from a .less file in the browser?
Regarding less.js, you can find the source of that file at: https://github.com/less/less.js/blob/master/dist/less-1.7.4.js
I understand that if one adds the attribute type="text/css" then they can be read using document.styleSheets but I have a hard time figuring out how to get the content of that element though.
Globally less.js uses two steps to do that:
first it will built a list of paths as follows:
//
// Get all <link> tags with the 'rel' attribute set to "stylesheet/less"
//
var links = document.getElementsByTagName('link');
less.sheets = [];
for (var i = 0; i < links.length; i++) {
if (links[i].rel === 'stylesheet/less' || (links[i].rel.match(/stylesheet/) &&
(links[i].type.match(typePattern)))) {
less.sheets.push(links[i]);
}
}
Then reads the content of these files by using a XMLHttpRequest too. See the doXHR function at line 7720 of less-1.7.4.js.

Dynamically load stylesheets

i know that you can have style-sheets in the head of a page, but i like to have them in a separate file. Now i'm working with a single page application.
Well in an SPA the content is dynamic, right? so i didn't want to import all the style-sheets in the head section with the link tag. Can i somehow import style-sheets as-and-when i need them?
I mean, can i have a link in the body, such that whenever my SPA loads some dynamic content, a style sheet also gets loaded? Such that i dont have to load all the stylesheets even when the dynamic content is not loaded..
I stress again: Whenever the content loads, the styles load.
I know i can do it with the help of an inline style like this:
~PSEUDO CODE
<tagname style="somestyle"></tagname>
but can i have some dynamic file imports too? Can i have the link tag in the body too? Even if it works, is it standard?
You should look into asychronously loading assets, such as the famous google-analytics code. You can load external stylesheets using Javascript.
JavaScript
(function(){
var styles = document.createElement('link');
styles.rel = 'stylesheet';
styles.type = 'text/css';
styles.media = 'screen';
styles.href = 'path/to/css/file';
document.getElementsByTagName('head')[0].appendChild(styles);
})();
Lines 1 and 7 create a new scope for variables such that local variables do not collide or override with globally scoped variables. It isn't necessary just a best practice. This solution also assumes you have a <head> tag in your html.
You can add/remove/edit link tags in your head area with java script to add/remove stylesheet files.
Code example:
Add a stylesheet to the head:
var newstyle = document.createElement("link"); // Create a new link Tag
// Set some attributes:
newstyle.setAttribute("rel", "stylesheet");
newstyle.setAttribute("type", "text/css");
newstyle.setAttribute("href", "filename.css"); // Your .css File
document.getElementsByTagName("head")[0].appendChild(newstyle);
To remove or edit a stylesheet you can give every stylesheet an id attribute and access it with this:
document.getElementById('styleid')
Or you can loop through all link tags in the head area and find the correct one but I suggest the solution with the ID ;)
Now you can change the href attribute:
document.getElementById('styleid').setAttribute("href", "newfilename.css");
Or you can remove the complete tag:
var styletorem = document.getElementById('styleid');
styletorem.parentNode.removeChild(styletorem)
I just tried to give dynamic styling to my webpage. I used a button. On click of it, the CSS will get imported using a method in Javascript.
In my html, I have:
<button type="button" onclick="changeStyle()"> CLICK TO SEE THE MAGIC!! </button>
Then in Javascript, I have a method named changeStyle():
function changeStyle()
{
var styles = document.createElement('link');
styles.type="text/css";
styles.rel="stylesheet";
styles.href="./css/style.css";
document.head.appendChild(styles);
}
It worked perfectly.

Include html file into another html file

Can someone guide me how to include html file with an html file. I have been trying to embed my file within object tags but to no avail.
Thanks!
You can use the iframe tag.
Another option is to used Server Side inclusion using SHTML, this require that the web server support it, see Server Side Includes
You are quite limited in HTML. You can use iframe tag but it's the same type of embedding as embedding of flash in html pages.
OT: It would be quite easy in PHP. Can you use it? Or do you need static web page?
Can you perhaps use Javascript to dynamically load it in?
You can have it loaded via JQuery as shown here: Include another HTML file in a HTML file
a.html:
<html>
<head>
<script src="jquery.js"></script>
<script>
$(function{
$("#includedContent").load("b.html");
});
</script>
</head>
<body>
<div id="includedContent"></div>
</body>
</html>
b.html:
<p> This is my include file </p>
May be this help:
Inside js/utils.js define functions:
function loadFileSync(fileName) {
var req = new XMLHttpRequest();
req.open('GET', fileName, false);
req.send(null);
if (req.status === 200) {
//console.log(req.responseText);
return req.responseText
} else
return "ERROR!!!"
}
function includeFile(fileName) {
document.write(loadFileSync(fileName))
}
And in main html file add this:
<script src="js/utils.js"></script>
<script> includeFile("navigation.html") </script>