Import entire HTML page into another page - javascript

I'm trying to embed another website within my website but I don't want to do it with an iFrame or AJAX import due to some issues that would cause.
<html>
<head>
<link rel="import" href="mysite.html">
</head>
<body>
<script>
var link = document.querySelector('link[rel="import"]');
var content = link.import;
document.body.appendChild(content.cloneNode(true));
</script>
</body>
</html>
Basically I'm trying to do this with HTML Imports from Web Components but unfortunately what I have above does not work (I am using the right browser too) and all the examples I've found were only for importing a specific div or element from within an imported page. But is it possible to simply load the entire page and embed it in another site?

It doesn't work because the object you get from the import property of the <link rel="import"> element is a Document interface.
You cannot insert this type of object inside a <body> element.
Instead you should at least get the <html> element of the imported document from its documentElement property:
var content = link.import.documentElement //returns a html element
But it still incorrect because you will then insert a <html> element inside a <body> element, which is ugly.
You'd rather copy the innerHTML text of the imported document to the main one:
document.body.innerHTML = link.import.querySelector( 'body' ).innerHTML
Or put the HTML you want to import inside a <template>, which is better if you want to defer scripts execution and loadings.

Related

Find and Replace text in an HTML iframe "srcdoc" attribute using Javascript

tldr: I'm looking to keep the other text in the srcdoc attribute of an iframe alone, but only swap out the link to the stylesheet using vanilla Javascript.
Longer version:
I'm customizing a Publii blog template and embedding a Cusdis comment widget using their hosted JS SDK.
Publii makes use of HTML, CSS, Javascript, and Handlebars.
The Cusdis widget works by pasting the following code in your html document:
<div id="cusdis_thread"
data-host="https://cusdis.com"
data-app-id="{{ APP_ID }}"
data-page-id="{{ PAGE_ID }}"
data-page-url="{{ PAGE_URL }}"
data-page-title="{{ PAGE_TITLE }}"
>
<script async src="https://cusdis.com/js/cusdis.es.js"></script>
Then, the Cusdis SDK will find the element with id cusdis_thread, then mount the iframe widget on it:
<iframe srcdoc='<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://cusdis.com/js/style.css">
<base target="_parent" />
<link>
<script>
window.CUSDIS_LOCALE = undefined
window.__DATA__ = {"host":"https://cusdis.com","appId":"...","pageId":"...","pageUrl":"...","pageTitle":"..."}
</script>
</head>
<body>
<div id="root"></div>
<script src="https://cusdis.com/js/iframe.umd.js" type="module"
</script>
</body>
</html>'
style="width: 100%; border: 0px none; height: 323px;">
#document
</iframe>
My issue is the following:
I want to edit the Cusdis widget's CSS so that the look goes better with my site.
I've tried editing my own stylesheet and selecting Cusdis's CSS classes, but the changes aren't reflected in the output (even with !important). I suspect that it's because the widget generates an iframe, and the elements I want to edit are contained in the iframe.
The workaround seems to be to replace the stylesheet in the iframe's "srcdoc" attribute with a link to another external stylesheet
Because the iframe is automatically generated by Cusdis's SDK, I can't edit that HTML on my end. I'm trying to find a way to replace the stylesheet in the generated iframe's srcdoc using vanilla Javascript.
Here is what I've tried:
Using setAttribute to replace the contents of the attribute:
document.querySelector("#cusdis_thread iframe").setAttribute('srcdoc', '<!DOCTYPE html><html><head><link rel="stylesheet" href="..."><base target="_parent" /><link><script> window.CUSDIS_LOCALE = undefined window.__DATA__ = {"host":"https://cusdis.com", appId":"...","pageId":"{{id}}","pageUrl":"{{url}}","pageTitle":"{{title}}"} </script> </head> <body> <div id="root"></div> <script src="https://cusdis.com/js/iframe.umd.js" type="module"> </script></body></html>');
Result: It worked in theory, but the comment section wasn't generated. When I inspected the code, the attribute's content was replaced. However, I'm using handlebars expressions {{}} to add the PAGE_ID, PAGE_URL, and PAGE_TITLE dynamically, but these expressions are kept inside the srcdoc (so, instead of the iframe displaying the actual URL in the window.__DATA__ =... section, it's still showing the handlebars expression {{url}}).
So, I'm looking for a solution which will keep the other text in the srcdoc attribute alone, but only swap out the link to the stylesheet. Here are my attempts at this:
Using .replace to find the url of Cusdis's stylesheet and replacing it with my own:
document.querySelector("#cusdis_thread iframe").replace("https://cusdis.com/js/style.css", "...");
Result: it was ignored
Using setAttribute for just the stylesheet:
document.querySelector("#cusdis_thread iframe").setAttribute('srcdoc', '<link rel="stylesheet" href="...">');
Result: it was ignored
Since this iframe is loaded through its srcdoc attribute, you can access its inner document from your own document, (because about:srcdoc is magic).
So the best will be to wait for the iframe to load, and to inject your own <link> in there (or modify the StyleSheets as you wish).
const iframe = document.querySelector("iframe");
iframe.addEventListener("load", (evt) => {
const link = document.createElement("link");
link.rel = "stylesheet";
link.href = "your-stylesheet.css";
iframe.contentDocument.head.append(link);
}, { once: true });
Live Demo (as a jsfiddle because StackSnippets null-origined iframes are dark-magic against same-origin...
The complicated part might be to detect when this iframe is inserted into the document. It seems you already are able to do so, but for the ones who can't, they could either check which event the library fires from, or in worst case scenario, use a MutationObserver.

How do I make the querySelector look in a specific included document only?

On my index page I have a number of includes.
<section><?php include('content/content1.php') ?></section>
<section><?php include('content/content2.php') ?></section>
<section><?php include('content/content3.php') ?></section>
In each of them I have a unique script (and some other things which is not shown here).
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Content1</title>
<link rel="stylesheet" href="content/sketch.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.10/p5.js"></script>
</head>
<body>
<div class="frame">
<canvas></canvas>
</div>
<script src="content/content1.js"></script>
</body>
The <canvas> tag is what the querySelector in the javascript calls to.
var canvas = document.querySelector('canvas');
This works, but only for the first content file. It seems the querySelector looks at the whole loaded page, instead of just inside the body of the document where the script is placed. Google console says: "Indentifier 'canvas' has already been declared".
I have tried setting an id on the canvas-element:
<canvas id="canvas1"></canvas>
var canvas = document.querySelector('#canvas1');
But it's not working. How do I get around this?
You can use document.currentScript to get the tag of the currently running script tag. From there, you can navigate to its containing section, and from there, get to the canvas descendant.
You should also put everything into an IIFE to avoid global variable collisions.
(() => {
const canvas = document.currentScript.closest('section').querySelector('canvas');
// ...
})();

How to render html from a external js file

This might be a dumb question but I have actually never done this and what I am trying is not working.
I have 2 files
test.html
test.js
I am linking the js as an external in test.html
<!doctype html>
<html>
<head>
<script type="text/javascript" src="test.js"></script>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
</body>
</html>
In my js file I have something like this
document.appendChild('<div>testing</div>')
I also tried
document.getElementsByTagName('body').appendChild('<div>testing</div>')
What I am doing wrong? I just want to learn how to generate html from an external js file for a future project I am working on.
You should generally try to run scripts that depend on the page after the document has been parsed, not before - if you put the script in <head> and run it immediately, the <body> has not been created yet. Give your script tag the defer attribute so that it only runs after the document is fully parsed:
<script defer type="text/javascript" src="test.js"></script>
appendChild accepts an element as a parameter, not a string
You need to append to the body, not the document itself (Only one element on document allowed.)
If you want to append an HTML string, assign/concatenate to the .innerHTML property
Assigning to .innerHTML will corrupt existing references to elements inside, including listeners. In order to keep listeners active, use insertAdjacentHTML instead:
document.body.appendChild(document.createElement('div'))
.textContent = 'testing1';
// Another method:
document.body.innerHTML += '<div>testing2</div>';
// Another method:
document.body.insertAdjacentHTML('beforeend', '<div>testing3</div>');

Open image using Java Script and call the function in html

I have two separate files one with my html code and with my javaScript. What I am trying to do is create a function in javascript then call that function in the html. Both files are in the same folder along with the image. I'm new to both languages and to this site so please go easy;
I would really appreciate it if someone could help me please.`
JavaScript to load image below:
var menu = new image();
menu.src = "Fitness App Entry Scrren.jpg"
function menuScreen(){
document.getElementById("menu").getAttribute("src");
}
Html code to call function:
<!DOCTYPE html>
<html>
<head>
<body src="Functions.js">
<script onload="menuScreen()"></script>
</body>
<head>
</html>
What you are doing is against the rules of HTML. First of all, <body></body> should be outside of <head></head>. You should have <script></script> in either <head></head> or <body></body>. The <body> tag should have the onload attribute set to menuScreen(), and the <script> tag's src attribute should be set to Functions.js (as John Hascall said). By the way, John Hascall is right, there is no element with the ID of "menu" so it won't work unless you create a <div> or <iframe> with the specific ID and append the image to it in your Functions.js file.
So, your JavaScript code should look like this:
var menu = new Image(); // note that the constructor is capitalized
menu.src = "Fitness App Entry Screen.jpg";
// Create a <div> with the image within it.
var division = document.createElement("div");
division.setAttribute("id", "menu");
division.appendChild(menu);
document.body.appendChild(division);
function menuScreen() {
division.getAttribute("src"); // you can use division because it has the id of menu
}
And here is your HTML code to run the page (according to the HTML5 specifications, note that):
<!DOCTYPE html>
<html>
<head>
<script src="Functions.js"></script>
</head>
<body onload="menuScreen()">
<!-- Left intentionally blank -->
</body>
</html>
Hopefully this will help you!

Why scripts at the end of body tag

I know this question was asked many times, but I haven't found answer. So why its recommended to include scripts at the end of body tag for better rendering?
From Udacity course https://www.udacity.com/course/ud884 - rendering starts after DOM and CSSOM are ready. JS is HTML parse blocking and any script starts after CSSOM is ready.
So if we got:
<html>
<head>
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>CRP</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<!-- content -->
<script src="script.js"></script>
</body>
</html>
CRP would be:
CSSOM ready > JS execute > DOM ready > Rendering
And if script is at head:
<html>
<head>
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>CRP</title>
<link rel="stylesheet" href="styles.css">
<script src="script.js"></script>
</head>
<body>
<!-- content -->
</body>
</html>
CRP would be the same:
CSSOM ready > JS execute > DOM ready > Rendering
This question is only about "sync" scripts (without async/defer attribute).
Scripts, historically, blocked additional resources from being downloaded more quickly. By placing them at the bottom, your style, content, and media could download more quickly giving the perception of improved performance.
Further reading: The async and defer attributes.
In my opinion, this is an outdated practice. More recently, the preference is for JavaScript to separate any code that requires the DOM to be present into a "DOMContentLoaded" event listener. This isn't necessarily all logic; lots of code can initialize without access to the complete DOM.
It's true that this causes a small moment when only the script file is being retrieved, and nothing else (for instance, images). This small window can be skipped by adding the async attribute, but even without it I recommend putting script tags in the head so that the browser knows as soon as possible to load them, rather than saving them (and any future JS-initiated requests) for last.
It is a best practice to put JavaScript tags just before the
closing tag rather than in the section of your HTML.
The reason for this is that HTML loads from top to bottom. The head
loads first, then the body, and then everything inside the body. If we
put our JavaScript links in the head section, the entire JavaScript
file will load before loading any of the HTML, which could cause a few
problems.
1.If you have code in your JavaScript that alters HTML as soon as the
JavaScript file loads, there won't actually be any HTML elements
available for it to affect yet, so it will seem as though the
JavaScript code isn't working, and you may get errors.
2.If you have a lot of JavaScript, it can visibly slow the loading of your page
because it loads all of the JavaScript before it loads any of the
HTML. When you place your JavaScript links at the bottom of your HTML
body, it gives the HTML time to load before any of the JavaScript
loads, which can prevent errors, and speed up website response time.
One more thing: While it is best to include your Javascript at the end
of your HTML , putting your Javascript in the of your
HTML doesn't ALWAYS cause errors. When using jQuery, it is common to
put all of your code inside a "document ready" function:
$("document").ready(function(){ // your code here });
This function basically says, don't run any of the code inside until
the document is ready, or fully loaded. This will prevent any errors,
but it can still slow down the loading time of your HTML, which is why
it is still best to include the script after all of the HTML.
Images placed below the script tag will wait to load until the JS script loads. By placing the script tag at the bottom you load images first, giving the appearance of a faster page load.
I think it depends on your website or app. Some web apps are based on JavaScript. Then it does not make sense to include it at the bottom of the page, but load it immediately. If JavaScript just adds some not so important features to some content based page, then better load it at the end. Loading time will almost be the same, but the user will see the important parts earlier (before the page finished loading).
It’s not about a whole site loading faster, but giving a user the impression of some website loading faster.
For example:
This is why Ajax based websites can give a much faster impression. The interface is always the same. Just some content parts will alter.
This was an extremely useful link. For any given webpage, a document object model is created from the .html. A CSS object model is also created from .css.
We also know that JS files also modify objects. When the browser encounters a tag, the creation of DOM and CSS object models are immediately halted when the script is run because it can edit everything. As a result, if the js file needed to extract information from either of the trees (DOM and CSS object model), it would not have enough information.
Therefore, script srces are generally at the end of the body where most of the trees have already been rendered.
Not sure if this helps,
But from this resource script-tag-in-web the inline script is always render blocking even if kept at the end of body tag.
Below inline script is first render blocking.Browser will not paint anything on screen till the long for loop is executed
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width,initial-scale=1" />
<link href="style.css" rel="stylesheet" />
<title>Critical Path: Script</title>
</head>
<body>
<p>Hello <span>web performance</span> students!</p>
<div><img src="awesome-photo.jpg" /></div>
<script>
let word = 0
for(let i =0; i<3045320332; i++){
word += i;
}
var span = document.getElementsByTagName('span')[0];
span.textContent = 'interactive'; // change DOM text content
span.style.display = 'inline'; // change CSSOM property
// create a new element, style it, and append it to the DOM
var loadTime = document.createElement('div');
loadTime.textContent = word + 'You loaded this page on: ' + new Date();
loadTime.style.color = 'blue';
document.body.appendChild(loadTime);
</script>
</body>
</html>
But'index.js' below is not initial render blocking, the screen will be painted , then once external 'index.js' is finished running the span tag will be updated.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width,initial-scale=1" />
<link href="style.css" rel="stylesheet" />
<title>Critical Path: Script</title>
</head>
<body>
<p>Hello <span>web performance</span> students!</p>
<div><img src="awesome-photo.jpg" /></div>
<script type="text/javascript" src="./index.js">
</script>
</body>
</html>
index.js
let word = 0
for(let i =0; i<3045320332; i++){
word += i;
}
var span = document.getElementsByTagName('span')[0];
span.textContent = 'interactive'; // change DOM text content
span.style.display = 'inline'; // change CSSOM property
// create a new element, style it, and append it to the DOM
var loadTime = document.createElement('div');
loadTime.textContent = word + 'You loaded this page on: ' + new Date();
loadTime.style.color = 'blue';
document.body.appendChild(loadTime);

Categories