Get time of page loading start in JavaScript - javascript

In JavaScript it is possible to wait for onLoad which may be used to specify the time of page loading completion.
Every HTTP response is sent along with Date: header which contains the time server sent a response.
Is there a way in JavaScript to get the time of page started loading?
Something similar to response Date: header.
It would be useful for cases when JavaScript is injected into page after some delay.

new Date(performance.timing.connectStart) in chrome, firefox, IE9, etc (caniuse)
demo
console.log(new Date(performance.timing.connectStart));

Try storing a value from var d= new Date(); var requested = d.getTime(); and execute it when the page loads.

<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
var loadDate;
</script>
</head>
<body onload="loadDate=new Date();">
<button onclick="alert(loadDate);">show load Date</button>
</body>
</html>

I would just pass a timestamp from the server-side script to the browser via a cookie or inline JS. E.g. in PHP:
<script>
var timestamp = new Date(<?php echo time(); ?>);
</script>

Related

How can I change my code to be able to calculate different urls instead of the current page

I'm trying to calculate the load time and page size of different URLs/Pages similar to the developer tools performance tab but in javascript. But the current code only calculates its current page instead of a different URL. Is there any way for me to do this because with my research I have no luck.
<html>
<head>
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Expires" content="0">
<script type="text/javascript">
var start = new Date().getTime();
function onLoad() {
var now = new Date().getTime();
var latency = now - start;
alert("page loading time: " + latency+"\n"+"Start time:"+start+"\n"+"End time:"+now);
alert("Load_size:"+document.getElementsByTagName("html")[0].outerHTML.length + "KB");
}
</script>
</head>
<body onload="onLoad()">
<!- Main page body goes from here. -->
</body>
</html>
It will not be possible to read the runtime parameters of a page outside the page your javascript is running on.
Part of the security model is to avoid being able to inspect the runtime of other pages. This is called the "sandbox". You'll need to build a plugin that breaks the sandbox to inspect the domLoad / domReady and other performance events.
Good news though, you probably have one built in! The console for modern browsers shows all those events in the timeline tab.
If you're trying to make a service that attempts to evaluate the runtime of other pages, you'll need to load those in a virtual web browser on the server and interpret the results using selenium or something similar.
You can try this to calculate the load time of a page:
<script type="text/javascript">
$(document).ready(function() {
console.log("Time until DOMready: ", Date.now()-timerStart);
});
$(window).load(function() {
console.log("Time until everything loaded: ", Date.now()-timerStart);
});
</script>
edit: this will only work on pages where this JS code will run, so if you cant insert code onto the page you wont be able to run it.

How to automatically refresh external data loaded into Javascript variables in HTML?

I have digital information written as Javascript variables by PHP into a .txt-File. This information gets changed by a user at a different interval.
var ISTUHSXDATE8 = '21.1.2018';
var ISTUHSXTIME8 = '20:11';
var ISTUHSXROT8 = 0;
var ISTUHSXGELB8 = 0;
var ISTUHSXGRUEN8 = 1;
var ISTUHSXAUSLASTUNG8 = '0%';
To show actual information in the HTML body, it´s necessary to make the HTML document load the latest version of .txt from server. [At the moment handmade by push the button and in webprojekt by setInterval() automatically]
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="expires" content="0">
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv='cache-control' content='no-cache'>
<script type="text/javascript" id="id_of_java_var"></script>
</head>
<body>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var dsts = new Date();
document.getElementById("id_of_java_var").src =
"https://www.juh-technik.de/StreifenstatusEA1.txt?time" + dsts.getTime();
}
</script>
</body>
</html>
With this code I can load latest version from the server for several .gif/.jpg/.html files by pushing the refresh button. The Problem is, this don´t works with .txt-files.
So my question is, how to refresh src of following line without page reload.
<script src="https://www.juh-technik.de/StreifenstatusEA1.txt" type="text/javascript" id="id_of_java_var"></script>
Thanks for your help :-)

Converting from "yyyy-MM-ddThh:mm:ss" to local showing different results in Google Chrome and IE

<!DOCTYPE html>
<html>
<head>
<title>Date Time Issue</title> </head> <body>
<script>
var dateInOtherFormat = "2017-02-02T13:00:00";
var localDate = new Date(dateInOtherFormat);
document.body.innerHTML = localDate;
</script>
</body>
</html>
Converting from "yyyy-MM-ddThh:mm:ss" format to local time showing different results in different browsers.
You can write a method for checking what the browser is. Then to the different browser use different code.

Refresh iFrame (Cache Issue)

We are getting a weird issue on which we are not sure what exactly cause it. Let me elaborate the issue. Suppose, we have two different html pages a.html and b.html. And a little script written in index.html:
<html>
<head>
<script>
function reloadFrame(iframe, src) {
iframe.src = src;
}
</script>
</head>
<body>
<form>
<iframe id="myFrame"></iframe>
<input type="button" value="Load a.html" onclick="reloadFrame(document.getElementById('myFrame'), 'a.html')">
<input type="button" value="Load b.html" onclick="reloadFrame(document.getElementById('myFrame'), 'b.html')">
</form>
</body>
</html>
A server component is continuously updating both files a.html and b.html. The problem is the content of both files are successfully updating on the server side. If we open we can see the updated changes but client getting the older content which doesn't show the updated changes.
Any idea?
Add this in a.html and b.html
<head>
<meta http-Equiv="Cache-Control" Content="no-cache" />
<meta http-Equiv="Pragma" Content="no-cache" />
<meta http-Equiv="Expires" Content="0" />
</head>
To force no cache checks
If you can add server-side instructions to those HTML files, you could send the appropriate headers to prevent caching:
Making sure a web page is not cached, across all browsers (I think the consensus is that the 2nd answer is best, not the accepted one)
Simone's answer already deals with Meta tags.
A cheap quick trick is to add a random number as a GET parameter:
page_1.html?time=102398405820
if this changes on every request (e.g. using the current time), reloading wil get forced every time, too.
Try something like the following:
<script>
var frameElement = document.getElementById("frame-id");
frameElement.contentWindow.location.href = frameElement.src;
</script>
This will force the iframe to be reloaded even if it was cached by the browser
I want to put Vishwas comment as a separate answer, extending
Pekka’s answer
//ensure iframe is not cached
function reloadIframe(iframeId) {
var iframe = document.getElementById(iframeId);
var d = new Date();
if (iframe) {
iframe.src = iframe.src + '?ver=' + d.getTime();
//alternatively frameElement.contentWindow.location.href = frameElement.src; //This will force the iframe to be reloaded even if it was cached by the browser
}
}
reloadIframe('session_storage_check');
Homero Barbosa's Solution worked like a charm. In my case, I had a varying number of iframes on the page, so I did the following:
$('.some_selector').each(function () {
var $randid = Math.floor(Math.random() * 101);
$(this).attr({'id': 'goinOnaSafari-' + $randid});
var $frame = document.getElementById('goinOnaSafari-' + $randid);
$frame.contentWindow.location.href = $frame.src;
});
I could not get the HTML to work.
<head>
<meta http-Equiv="Cache-Control" Content="no-cache" />
<meta http-Equiv="Pragma" Content="no-cache" />
<meta http-Equiv="Expires" Content="0" />
</head>
For development in chrome I checked the console Network tab and found where the iframe is loaded.
I confirmed that it was loaded with a 304 response wich means it loads from cache.
Right click -> clear browser cache.
Will not work in production, but at least helps with development.
For one possible solution to this, pass a "cache parameter" to your calls to a.html and b.html. For example
HTML
<input type="button" value="Load a.html" onclick="cacheSafeReload('a.html');">
Javascript
function cacheSafeReload(urlBase) {
var cacheParamValue = (new Date()).getTime();
var url = urlBase + "?cache=" + cacheParamValue;
reloadFrame(document.getElementById('myFrame'), url);
}

Why does this javascript code prevent my browser from ever loading?

I'm learning javascript and jquery and have written a very basic script inside my file. I'm experiencing two problems...
The browser never finishes loading the document, it just sits there with the loading icon animating in the tab. Any ideas?
I can't seem to debug this using firebug. When I set a breakpoint anywhere in the document load function, it never hits. Any ideas?
Here's my code...
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link media="screen" type="text/css" href="default.css" rel="stylesheet">
<script src="jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function()
{
var strMarkup = "";
var strXMLFile = "";
//Parse XML and generate accordion elements
var arrayAccordianElements = ParseXML(strXMLFile);
});
function ParseXML(strPath)
{
var arrayEvents = new Array();
arrayEvents[0] = "test1";
arrayEvents[1] = "test2";
arrayEvents[2] = "test3";
//Return the accordian elements
return arrayEvents;
}
</script>
</head>
<body>
hello
</body>
</html>
As you experts can see, my webpage should simply display "hello" after processing some javascript that creates an array inside of a function. Do you see any problems? I apologize if they're obvious problems, I'm a noob :)
Thanks in advance for all your help!
Runs fine for me in Safari 4.0.3. Make sure your path to jQuery is correct? If it is incorrect and there's something misconfigured and jQuery fails to load, that will hang indefinitely.
Code-wise I don't see anything that would cause an infinite loop at all. However, knowing firefox etc, there may be a variety of things out of your control. Start with restarting the browser. Profile the script with Firebug (Console > Profile > Reload the page > Press profile again), and see what part takes most time.
One thing, probably unrelated, close your link tag. is sufficient.

Categories