web page loading time - javascript

var startTime = new Date().getTime();
var myWin = window.open("http://www.hizlial.com/hediyelik/hediyelik-urunler/zippo-jack-daniels-ltr-flask-hediye-seti_16.004.4126.1233.htm","_blank")
window.onload = function() { opener.window.endtime = new Date().getTime(); }
var endTime = opener.window.endtime;
var timeTaken = endTime-startTime;
document.write(timeTaken);
i edited the new code but this time i couldnt write the timeTaken value? so whats wrong here?

That's because javascript isn't a threaded language, meaning that it doesn't wait for things to happen, it will open the page and while the page is loading will go on and do other stuff. What you would need to do is to add this into the target page:
window.onload = function() { window.opener.endtime = new Date().getTime(); }
Or as ramazan murat wrote:
var startTime = new Date().getTime(); var myWin = window.open("www.mozilla.com");
window.onload = function() { opener.window.endtime = new Date().getTime(); };
var timeTaken = endTime-startTime;
Another way to go about this would be to do this:
<script>start = new Date().getTime();</script>
<iframe src="http://www.mozilla.com/" onload="end=new Date().getTime();"></iframe>

I would use Net in Firebug to test a page's load time.

Use Google Chrome's developer tool's timeline function.

If you don't need to do this programmatically, then Firebug's Net tab will give you all the information you need to know about how long given resources on a page take to request.

Related

Disqus this.callbacks.onNewComment not working

I somehow cannot get the Disqus this.callbacks.onNewComment to work. What could be wrong? Im trying to alert('hey!') once a new comment is posted. Source
<script>
var disqus_config = function () {
this.page.url = PAGE_URL;
this.page.identifier = PAGE_IDENTIFIER;
this.callbacks.onNewComment = [function(comment) {
alert(comment.id);
alert(comment.text);
alert('hey!');
}];
};
(function() { // DON'T EDIT BELOW THIS LINE
var d = document, s = d.createElement('script');
s.src = 'https://example.disqus.com/embed.js';
s.setAttribute('data-timestamp', +new Date());
(d.head || d.body).appendChild(s);
})();
PAGE_URL and PAGE_IDENTIFIER need to be specific to your site
This callback is for detecting a new post by this browser window. Not new posts arriving from other users (or even your own user in another browser windows)
That 2nd one threw me as I thought it was to indicate new post had arrived

Antlr4 Javascript Visitor

I'm currently trying to develope a JavaScript Compiler with the help of an Antlr4 Visitor. I've got this already implemented with Java but cannot figure out how to do this in JavaScript. Probably somebody can answer me a few questions?
1: In Java there is a Visitor.visit function. If im right this isn't possibile with Javascript. Is there a work around for this?
2: My Javascript Visitor got all the generated visiting functions but when I use console.log(ctx) the context is undefined. Any idea why?
Extract from the SimpleVisitor.js:
// Visit a parse tree produced by SimpleParser#parse.
SimpleVisitor.prototype.visitParse = function(ctx) {
console.log(ctx);
};
Main js file:
var antlr4 = require('lib/antlr4/index');
var SimpleLexer = require('antlr4/SimpleLexer');
var SimpleParser = require('antlr4/SimpleParser');
var SimpleVisitor = require('antlr4/SimpleVisitor');
var input = "double hallo = 1;";
var chars = new antlr4.InputStream(input);
var lexer = new SimpleLexer.SimpleLexer(chars);
var tokens = new antlr4.CommonTokenStream(lexer);
var parser = new SimpleParser.SimpleParser(tokens);
var visitor = new SimpleVisitor.SimpleVisitor();
parser.buildParseTrees = true;
var tree = parser.parse();
visitor.visitParse();
This is probably enough to start with ...
Bruno
Edit:
Probably the context is undefined because I call the function without arguments but where do I get the "starting"-context?
Edit2:
So I think I get the idea how this should work out. One Question remaining how do I determine which rule to call next inside each visitor function?
The basic idea behind the visitor is that you have to handle all the logic by yourself. To do this I generated the visitor using antlr. My own visitor overrides all functions that I need to implement my logic.
create lexer, tokens, ...
var antlr4 = require('antlr4/index');
var SimpleJavaLexer = require('generated/GrammarLexer');
var SimpleJavaParser = require('generated/GrammarParser');
var SimpleJavaVisitor = require('generated/GrammarVisitor');
var Visitor = require('./Visitor');
var input = "TestInput";
var chars = new antlr4.InputStream(input);
var lexer = new GrammarLexer.GrammarLexer(chars);
var tokens = new antlr4.CommonTokenStream(lexer);
var parser = new GrammarParser.GrammarParser(tokens);
var visitor = new Visitor.Visitor();
parser.buildParseTrees = true;
var tree = parser.parse();
and call your entry function
visitor.visitTest(tree);
inside your new visitor you need to implement your new logic to determine which function to call next (the right context as argument is important)
var GrammarVisitor = require('generated/GrammarVisitor').GrammarVisitor;
function Visitor () {
SimpleJavaVisitor.call(this);
return this;
};
Visitor.prototype = Object.create(GrammarVisitor.prototype);
Visitor.prototype.constructor = Visitor;
Visitor.prototype.visitTest = function(ctx) {
// implement logic to determine which function to visit
// then call next function and with the right context
this.visitBlock(ctx.block());
};
I hope you can understand my basic idea. If anybody got any questions just comment.

How would I run a function on load in javascript once per a day?

Let's say it's June 18 and a person runs the javascript and it runs a function on load but it doesn't run the function later that day even if the person closes the window or program in my case.
However, on June 19 if the person opens the program and it runs the javascript then it runs the function because it's a new day and hasn't run that day yet...
So basically, how do I make an onload function only work once per a day?
It has to be javascript because the program I'm using can only be assisted by javascript files and nothing else.
The person has to download the files to their computer so how would I go about saving and retrieving the localStorage?
You can use localStorage to achieve this. Sample Code:
/* returns null if local storage is not defined */
var localVal = localStorage.getItem('someUniqueName');
if(localVal == null){
// execute the function
}else{
var tempd = new Date();
var str = tempd.getDay() + tempd.getMonth() + tempd.getFullYear();
if(localVal.localeCompare(str) == -1){
//execute function
localStorage.setItem('someUniqueName',str);
}
}
If you wish to create a cookie and handle it, then you may go through this question
You can create a cookie on the user's browser that persists till the end of the day. If you are using jQuery, you can do as follows ( taken from here ):
var currentDate = new Date();
expirationDate = new Date(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate()+1, 0, 0, 0);
$.cookie("ultOS", "5", {expires: expirationDate});
If you are using plain javascript, then the way to do this would be as follows (from here):
function createCookie(name,value,date) {
if (date) {
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
var today = Date();
var midnight = today.getDate()+1
midnight.setHours(0,0,0,0);
createCookie("Valid","true",midnight);
At the beginning of every page load, just check the value of this cookie.

How to ask javascript to wait an end of executing external application?

Colls, hello.
My javascript run an external .bat file:
var objShell = new ActiveXObject("Shell.Application");
objShell.ShellExecute("start.bat", "Main.bat c:\pr ext.dat ", "C:\\PR\\", "open", "1");
Start.bat file works five minutes. And after that my script continue execute other commands.
My question is «how to ask (let him know) javascript to wait an end of executing Start.bat file?»
The naxt code is not very suitable in my case:
var date = new Date();
var curDate = null;
do { curDate = new Date(); }
while(curDate-date < millis);
If you're sure about the time your Main.bat needs to execute, you can use this:
WScript.Sleep(50000);
WSH Language reference: http://msdn.microsoft.com/en-us/library/98591fh7(v=vs.84).aspx
Sleep method: http://msdn.microsoft.com/en-us/library/6t81adfd(v=vs.84).aspx

Browser crashes after 10-15 mins

In my app I'm displaying 10 charts (charts are from dygraphs.) to monitor data. For displaying charts I'm getting data from my sever by sending ajax request to 4 servlets on every 5 seconds. After 10-15 mins (don't know exact time.) my browser crashes saying "aw!! snap." What could be the reason? Is it javascript that is causing it? or is it because I'm sending request every 5 seconds?
Browser tested: Firefox and Chorme.
Note:- When I refresh the browser after crash it again works fine for 10-15 mins.
JS code:
var i=0;
var loc = new String();
var conn = new String();
var heapUsage = new String();
var cpuUsage = new String();
var thrdCnt = new String();
var heapUsageConsole = new String();
var cpuUsageConsole = new String();
var thrdCntConsole = new String();
var user = new String();
var MemTotal = new String();
function jubking(){
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
var url = "MonitorDBServlet";
xmlhttp.open("POST", url, false);
xmlhttp.send(null);
var str = xmlhttp.responseText;
var strArr = str.split(",");
url = "MonitorTomcatServlet";
xmlhttp.open("POST", url, false);
xmlhttp.send(null);
var appstr = xmlhttp.responseText;
var appArr = appstr.split(",");
url = "MonitorConsoleTomcatServlet";
xmlhttp.open("POST", url, false);
xmlhttp.send(null);
var appstrConsole = xmlhttp.responseText;
var appArrConsole = appstrConsole.split(",");
url = "CpuMemoryServlet";
xmlhttp.open("POST", url, false);
xmlhttp.send(null);
var statesStr = xmlhttp.responseText;
var states = statesStr.split(",");
if(i>30){
loc = loc.substring(loc.indexOf("\n")+1);
loc += i+","+strArr[0]+","+strArr[1]+"\n";
//--- Do same thing all other var
} else {
loc += i+","+strArr[0]+","+strArr[1]+"\n";
//--- Do same thing all other var
}
document.getElementById("dbSize").innerHTML = strArr[3];
document.getElementById("HeapMemoryUsageMax").innerHTML = appArr[1];
document.getElementById("HeapMemoryUsageMaxConsole").innerHTML = appArrConsole[1];
g = new Dygraph(document.getElementById("dbLocks"),
",locksheld,lockswait\n"+loc+"");
g = new Dygraph(document.getElementById("activeConnection"),
",Connections\n"+conn+"");
g = new Dygraph(document.getElementById("example2"),
",heapUsage\n"+heapUsage+"");
g = new Dygraph(document.getElementById("example3"),
",cpuUsage\n"+cpuUsage+"");
g = new Dygraph(document.getElementById("example4"),
",thread,peakThread\n"+thrdCnt+"");
g = new Dygraph(document.getElementById("example6"),
",heapUsage\n"+heapUsageConsole+"");
g = new Dygraph(document.getElementById("example7"),
",\n"+cpuUsageConsole+"");
g = new Dygraph(document.getElementById("example8"),
",thread,peakThread\n"+thrdCntConsole+"");
g = new Dygraph(document.getElementById("cpuStates"),
",user,system,nice,idle\n"+user+"");
g = new Dygraph(document.getElementById("memStates"),
",MT,MF,B,C,ST,SF\n"+MemTotal+"");
i = i + 1;
setTimeout("jubking()", 5000);
}
You can use about:crashes in FF to view the specific reason for your crash. As mentioned by others, you could be leaking memory if you're caching off data (assigning it to a variable) returned by your AJAX call and not clearing it when the next call is made.
Edit:
Just saw your comment - 1,923,481 K is definitely too much - you're leaking data somewhere. What OS are you running? If you run FF from console in *nix, you usually get some form of a dump into console when something's going wrong (not sure about Windows).
You could possibly try decreasing your poll intervals to once every few seconds and step through the script using Firebug or Chrome's debugger to see what's happening. Worst case, start commenting things out until you figure out exactly what is making your app crash. And then, figure out a way to fix it :)
I suspect that your dygraphs usage is, as you note in your comments, the source of your trouble. It looks like you're binding new graphs over and over again when you only want to update the data, using a moving window for the data would also help. Try reworking your updater to work like this pseudo-JavaScript:
var graphs = {
dbLocks: {
graph: new DyGraph(/* ... */),
data: [ ]
},
activeConnection: {
graph: new DyGraph(/* ... */),
data: [ ]
},
// etc.
};
var DATA_WINDOW_SIZE = 1000; // Or whatever works for you.
function update(which, new_data) {
var g = graphs[which];
g.data.push(new_data);
if(g.data.length > DATA_WINDOW_SIZE)
g.data.shift();
g.graph.updateOptions({ file: g.data });
}
function jubking() {
// Launch all your AJAX calls and bind a callback to each
// one. The success callback would call the update() function
// above to update the graph and manage the data window.
// Wait for all the above asynchronous AJAX calls to finish and
// then restart the timer for the next round.
setTimeout(jubking, 5000);
}
The basic idea is to use window on your data with a reasonable maximum width so that the data doesn't grow to chew up all your memory. As you add a new data point at the end of your data cache, you drop old ones off the other end once you hit your maximum comfortable size.
You can find some techniques for waiting for several asynchronous AJAX calls to finish over here: How to confirm when more than one AJAX call has completed? (disclosure: yes, that's one of my other answers).
The answer above advocates re-using your Dygraph object and calling g.updateOptions({file:...}) to reduce memory usage. This is a great way to do it.
The other way is to call g.destroy() before you redefine the Dygraph object. This will make dygraphs clear out all of its internal arrays and DOM references. Example:
g = new Dygraph(...);
g.destroy();
g = new Dygraph(...);
Read more here: http://blog.dygraphs.com/2012/01/preventing-dygraphs-memory-leaks.html

Categories

Resources