I want to display the loading time of a webpage on site. I can get this working by writing to console.log but writing the information to a page is beyond me.
In my head I have
<!-- Loading Time -->
<script type="text/javascript">
var loadTime = window.performance.timing.domContentLoadedEventEnd- window.performance.timing.navigationStart;
</script>
Then I have this to write to the console log
<script type="text/javascript">
window.onload = function () {
var loadTime = window.performance.timing.domContentLoadedEventEnd-window.performance.timing.navigationStart;
console.log('Page load time is '+ loadTime / 1000);
}
</script>
This works perfectly but I really want to display the loading time on a webpage. How do I achieve this? My page is a simple html / css site.
Three possible methods are:
Just writing to the document directly (should not be used because of the reasons described here):
document.write(loadTime);
Adding an HTML element and setting its inner text to loadTime:
function displayLoadtime(loadtime){
document.getElementById("loading-time").innerText = loadtime;
}
<p id='loading-time'>Loading...</p>
Creating the element in Javascript and displaying the loadTime using it:
function displayLoadingtime(loadtime){
let p = document.createElement("p");
p.innerText = loadtime;
document.getElementById("loading-time-container").appendChild(p);
}
<div id='loading-time-container'></div>
I know what I answered is some beginners' stuff and you probably know it, but I will edit the answer in case you give more details, because I don't see any problems in displaying it if you already have the loadTime.
You can write the time you calculated into an element of the webpage using the innerText property of a Node.
window.onload = function() {
var loadTime = window.performance.timing.domContentLoadedEventEnd - window.performance.timing.navigationStart;
console.log('Page load time is ' + loadTime / 1000);
performanceDisplay = document.getElementById("performance-display") // get a reference to the paragraph
performanceDisplay.innerText = loadTime / 1000 // put the value of the variable loadTime into the paragraph
}
<body>
<p id="performance-display"></p>
</body>
Or, if you do not want to put the paragraph manually into the HTML, you can create it in the JavaScript using document.createElement:
window.onload = function() {
var loadTime = window.performance.timing.domContentLoadedEventEnd - window.performance.timing.navigationStart;
console.log('Page load time is ' + loadTime / 1000);
performanceDisplay = document.createElement("p") // create a new paragraph element
performanceDisplay.innerText = loadTime / 1000 // put the value of the variable loadTime into the paragraph
document.body.appendChild(performanceDisplay) // add the paragraph element to the body of the document
}
Welcome to StackOverflow, Rylad!
You can easily put it into your webpage by referencing an HTML element.
Ie. add an element with the id timeContainer to your page and set its innerHTML to your variable, loadTime. Here's an example:
<body>
<span id="timeContainer">
The load time will be displayed here when the page is finished loading
</span>
<script type="text/javascript">
window.onload = function() {
var loadTime = window.performance.timing.domContentLoadedEventEnd - window.performance.timing.navigationStart;
console.log(loadTime)
document.getElementById("timeContainer").innerText = loadTime;
}
</script>
</body>
Try this,
Simple way to get loading time
<body>
<span id="loadingTime"></span>
<script>
window.addEventListener('load', (e) => {
let timestemp = new Date(e.timeStamp).getTime()
console.log('loading time is', timestemp)
document.getElementById('loadingTime').innerText = "loading time is "+timestemp
})
</script>
</body>
Related
My aim is to have a single web page which changes back and forth between two pieces of code every 60 seconds. I am able to do this with two urls/webpages using content refresh, however, ideally I am trying to include it all in one javascript file.
page1content and page2content indicate where I would want to insert the html code within the array. The HTML code is run within a js filter using Rhapsody Integration engine.
Any thoughts on how I might be able to get html content to switch between the two in a continous loop?
var next = output.append(input[0]);
var html = "";
html = html + "<style>";
html = html + "<span id=\"flicker\"></span>";
html = html + "</style>";
var pageContent = ["page1content", "page2content"];
var count = 0;
function changeContent() {
$("#flicker").text(pageContent[count]);
count < 2 ? count++ : count = 0;
}
setInterval(changeContent, 60000);
XMLData.setText(HTMLBody,'UTF8');
Try the snippet below:
const pageContent = [
` <p>This is from page 1.</p>
<p>This is another paragraph from page 1.</p>`,
` <p>This is from page 2.</p>
<p>This is another paragraph from page 2.</p>`];
let count = 0;
function changeContent() {
$("#flicker").html(pageContent[count]);
count++; count %= 2;
}
setInterval(changeContent, 5000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="flicker"></div>
P.S: Setting the interval to 5 seconds to showcase the functionality more quickly
The following is the outline of www.abc.com/index.html
<html>
<head>
..
..
</head>
<body>
<script>
var js1 = document.createElement('script');
js1.type = "text/javascript";
js1.async = true;
js1.src = "cdn/js1.js";
document.getElementsByTagName('head').appendChild(js1);
console.log('Start: ' + new Date().getTime());
</script>
<img src="img1.jpg">
<img src="img2.jpg">
....
</body>
</html>
This is the contents of js1.js
console.log('End: ' + new Date().getTime());
var img = new Image();
img.src = "img3.jpg";
var f1 = function() {
..
}
var f2 = function() {
..
}
...
The observation is that there is a pretty large difference being observed between the 'End' and 'Start' outputs. In the browser network tab, I find that this is the order of network requests being made:
js1.js
img1.jpg
img2.jpg
img3.jpg
The question is - why does it take so long for the script to begin executing? I tried removing the other images from the page, this causes the script to execute much quicker. Why do the other requests execute before the script executes (I find this happens even if the call is made synchronously)? Is there a way to make the script execute completely first before the rest of the page does?
I am currently working on features that infuencent web loading. I succeeded
to find a script that displays those .But my problem how to execute this script on the page that will open by clicking href
<html>
<head>
<script type="text/javascript">
// Add load event listener.
window.addEventListener("load", loadTime, false);
function loadTime() {
var x = performance.timing.connectEnd+"f";
// Get current time.
var now = new Date().getTime();
// Calculate page load time.
var page_load_time = now - performance.timing.navigationStart;
// Write the load time to the F12 console.
if (window.console) { console.log(window.performance.timing);
window.alert(x)}
}
</script>
<script>
var someAnchor = document.getElementById('someAnchor');
someAnchor.onclick = function(){
loadTime();
};
function loadTime() {
// Get current time.
var now = new Date().getTime();
// Calculate page load time.
var page_load_time = now - performance.timing.navigationStart;
// Write the load time to the F12 console.
if (window.console) {
console.log(window.performance.timing);
}
}
</script>
</head>
<body>
<a id="someAnchor" target="_blank" href="https://www.youtube.com/">youtube</a>
</body>
</html>
The first script shows these carachteristics on current page but the second does not work on load youtube page
so you basically just want to run your function upon clicking an anchor?
var someAnchor = document.getElementById('someAnchor');
someAnchor.onclick = function(){
loadTime();
};
function loadTime() {
// Get current time.
var now = new Date().getTime();
// Calculate page load time.
var page_load_time = now - performance.timing.navigationStart;
// Write the load time to the F12 console.
if (window.console) {
console.log(window.performance.timing);
}
}
<a id="someAnchor" href="#">some anchor</a>
What you want to do is illegal and impossible, because of security reasons, once you close a page or navogate away from it, every javascript function will stop immedialitely. Just imahine what would happen, if a page would navigate you back every time you leave it.
The images named One.jpg to Ten.jpg are in a folder 'myFolder', which is at my desktop. Below is a code to rotate three images at a time from the total ten in myFolder and the html file is also in the same folder. How to write the src so that this code may work. Alert message gives the name of these 10 images, but further it does not work. Script does not work placed in body tags. What is wrong which is to be corrected for expedted results.
<html>
<body>
<img id = "im1"><img id = "im2"><img id = "im3">
<script type = "text/javascript">
var imgArray = ['One.jpg','Two.jpg','Three.jpg','Four.jpg','Five.jpg', 'Six.jpg', 'Seven.jpg', 'Eight.jpg', 'Nine.jpg', 'Ten.jpg'];
function randOrd(){return (Math.round(Math.random())-0.5)}
imgArray.sort(randOrd);
alert (imgArray); // FOR TESTING
var len = imgArray.length;
var count = 0;
rotate1();
rotate2();
rotate3();
function rotate1() {
document.getElementById("im1").src= imgArray[count];
count++;
if (count>=len) {count = 0}
var tim1 = window.setTimeout("rotate1()", 3000); // 3 seconds
}
function rotate2() {
document.getElementById("im2").src = imgArray[count];
count++;
if (count>=len) {count = 0}
var tim2 = window.setTimeout("rotate2()", 5000); // 5 seconds
}
function rotate3() {
document.getElementById("im3").src = imgArray[count];
count++;
if (count>=len) {count = 0}
var tim3 = window.setTimeout("rotate3()", 7000); // 7 seconds
}
</script>
</body>
</html>
A best-practice says that the script should be taken out in a separate file and then included at the end of the body like this:
<script src="scripts/YourScript.js"></script>
where src points to the file.
This is good because:
the browser renders the page as it parses it from top to bottom. This means that when it reaches the script part at the end of the body tag, your HTML should be loaded, so the elements used by your scripts will most likely be present.
you can display something to the user until the slowest part (the scripts) load.
you could server the scripts from a CDN so the request-response delay would be minimum.
The only exception to this rule I know of is modernizr or similar browser and feature detection libraries.
Update
You are missing a semicolon here:
if (count>=len) {count = 0}
it should be like:
if (count>=len) {count = 0; }
Also, when you pass the function to the setTimeout you can do it like:
window.setTimeout(rotate3, 7000);
Ideally, you'd load your script from an external file and there'd be no JavaScript at all in your HTML file. Then you'd serve your documents with CSP headers.
Ignoring the "best" practice thing, your problem is that you have no closing </script> tag.
I have a page that is loading a script from a third party (news feed). The src url for the script is assigned dynamically on load up (per third party code).
<div id="div1287">
<!-- dynamically-generated elements will go here. -->
</div>
<script id="script0348710783" type="javascript/text">
</script>
<script type="javascript/text">
document.getElementById('script0348710783').src='http://oneBigHairyURL';
</script>
The script loaded from http://oneBigHairyURL then creates and loads elements with the various stuff from the news feed, with pretty formatting, etc. into div1287 (the Id "div1287" is passed in http://oneBigHairyURL so the script knows where to load the content).
The only problem is, it only loads it once. I'd like it to reload (and thus display new content) every n seconds.
So, I thought I'd try this:
<div id="div1287">
<!-- dynamically-generated elements will go here. -->
</div>
<script id="script0348710783" type="javascript/text">
</script>
<script type="javascript/text">
loadItUp=function() {
alert('loading...');
var divElement = document.getElementById('div1287');
var scrElement = document.getElementById('script0348710783');
divElement.innerHTML='';
scrElement.innerHTML='';
scrElement.src='';
scrElement.src='http://oneBigHairyURL';
setTimeout(loadItUp, 10000);
};
loadItUp();
</script>
I get the alert, the div clears, but no dynamically-generated HTML is reloaded to it.
Any idea what I'm doing wrong?
How about adding a new script tag to <head> with the script to (re)load? Something like below:
<script>
function load_js()
{
var head= document.getElementsByTagName('head')[0];
var script= document.createElement('script');
script.src= 'source_file.js';
head.appendChild(script);
}
load_js();
</script>
The main point is inserting a new script tag -- you can remove the old one without consequence. You may need to add a timestamp to the query string if you have caching issues.
Here's a method which is similar to Kelly's but will remove any pre-existing script with the same source, and uses jQuery.
<script>
function reload_js(src) {
$('script[src="' + src + '"]').remove();
$('<script>').attr('src', src).appendTo('head');
}
reload_js('source_file.js');
</script>
Note that the 'type' attribute is no longer needed for scripts as of HTML5. (http://www.w3.org/html/wg/drafts/html/master/scripting-1.html#the-script-element)
Creating a new script tag and copying the contents of the existing script tag, and then adding it, works well.
var scriptTag = document.createElement('script');
scriptTag.innerText = "document.body.innerHTML += 'Here again ---<BR>';";
var head = document.getElementsByTagName('head')[0];
head.appendChild(scriptTag);
setInterval(function() {
head.removeChild(scriptTag);
var newScriptTag = document.createElement('script');
newScriptTag.innerText = scriptTag.innerText;
head.appendChild(newScriptTag);
scriptTag = newScriptTag;
}, 1000);
This won't work if you expect the script to change every time, which I believe is your case. You should follow Kelly's suggestion, just remove the old script tag (just to keep the DOM slim, it won't affect the outcome) and reinsert a new script tag with the same src, plus a cachebuster.
Small tweak to Luke's answer,
function reloadJs(src) {
src = $('script[src$="' + src + '"]').attr("src");
$('script[src$="' + src + '"]').remove();
$('<script/>').attr('src', src).appendTo('head');
}
and call it like,
reloadJs("myFile.js");
This will not have any path related issues.
Use this function to find all script elements containing some word and refresh them.
function forceReloadJS(srcUrlContains) {
$.each($('script:empty[src*="' + srcUrlContains + '"]'), function(index, el) {
var oldSrc = $(el).attr('src');
var t = +new Date();
var newSrc = oldSrc + '?' + t;
console.log(oldSrc, ' to ', newSrc);
$(el).remove();
$('<script/>').attr('src', newSrc).appendTo('head');
});
}
forceReloadJS('/libs/');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
I know that is to late, but I want to share my answer.
What I did it's save de script's tags in a HTML file,
locking up the scripts on my Index file in a div with an id, something like this.
<div id="ScriptsReload"><script src="js/script.js"></script></div>
and when I wanted to refresh I just used.
$("#ScriptsReload").load("html_with_scripts_tags.html", "", function(
response,
status,
request
) {
});