Report the time spent on a page to the server - javascript

Is it possible to report the time spend on a page back to server when the visitor leaves the page by closing the tab or the browser? Using Javascript.
And it will work on Firefox, Google Chrome, Safari, Opera, and IE8 (IE7 and 6 are not important).
But it will work in any case; even while the browser is closing, or it is typed another address.

You can try windows.onbeforeunload but there is no guarantee that it will work in all cases.
Anyway I suggest you use google analytics which has that feature among many others (I doubt you can do better than google!). It's free.

If you want to implement this yourself, you need to decide when to get the start time--you can put a script tag at the top of the page, which may execute before the content has rendered, on the onload event, which will wait until all images and scripts have loaded, or something like the JQuery ready event, which occurs when the DOM is ready, but doesn't wait for resources to load. At this point, you'd want to record a start time:
<script>var startTime = new Date().getTime();</script>
Then you can listen for the onunload or onbeforeunload event and use an image to send a GET request with the info:
<script>
window.onunload = function() {
var i = new Image();
var timeSpentMilliseconds = new Date().getTime() - startTime;
i.src = '/pagetime?timespent=' + timeSpentMilliseconds;
}
</script>
You'll have to do some testing to see whether the requests are always sent--I'm sure sometimes the browser closes or the tab switches before they finish firing.

You could also try PiWik which offers you similar statistics about the visitor of you website.

Why not use Google Analytics directly?
Besides what you want, it provides much more data for your analytics.
And, it is free.
Regards,
freezea.

Related

Javascript running only once on Internet Explorer, runs properly when developer tools is open

We have an unusual problem with javascript running on IE 11. I tried it on one of our servers running IE8 and the same problem occurs. However, it runs fine on Chrome and Mozilla.
Here's the code in question:
SetGuideFatningCookie(fid); //set a cookie according to user choice
var validFatningCombo = ValidFatningCheck(); //ask server if user choice is valid using XMLHttpRequest GET request
if(validFatningCombo)
window.location.href = GetGuideTilbehoerURL(); //if valid redirect user to next page
else
popAutoSizeFancy("#GLfancy"); //if not show a fancybox with error text
The user chooses one of 7 choices. Then they click a button that runs the above code. The code sets a cookie containing the user's choice and asks the server if the choice is valid. If valid - we redirect the user and if not, we open a fancybox that contains some error text and two buttons - "Try again"(closes box and they can try again) and "Send us a message"(redirects user to our "ask us a question" page).
The code runs fine the first time the user goes to this process.
However, if they have chosen an invalid choice, they close the fancybox and try to choose another choice and continue -> then the fancy box appears ALWAYS, regardless of what the user chooses.
If they choose a valid choice and continue, get redirected to next page, then come back to this page and choose an invalid choice and press continue -> then they can continue to the next page without fancybox ever coming up.
However, if IE's developer tools are opened, the code runs correct every single time.
I have found many threads describing this is a problem with console.log. I have removed every single reference to console.log from all our .js files. It could be one of the external libraries that we are using, like jquery, modernizr, fancybox and menucool's tooltip library.
Therefore I tried including a console fallback function for IE, like this thread suggests:
Why does JavaScript only work after opening developer tools in IE once?
I am currently trying with this one, and I have tried every single other fallback console replacement from the thred I link to.
if (!window.console) window.console = {};
if (!window.console.log) window.console.log = function () { };
I tried including it:
Somewhere in our .js files
script element in head after loading all our .js files and all external libraries
script element in head before loading all our .js files and all external libraries
Inside $(document).ready(function() {}); , in a script element in head after loading all other js
So far, none of the fallback pieces of code I have tried in any of these 4 locations have solved the problem. It always behaves the same way in IE. I couldn't find another explanation than the "console" one for this problem so far, so if anyone got any insight on it, it would be greatly appreciated.
EDIT: I will include some more info:
The very act of opening Developer Tools removes the unwanted behaviour. No errors are ever shown in console.
I checked the server side to see if the server is getting the call from ValidFatningCheck(); It turns out that the call is made only the first time (or if Developer tools is open - every time) which is rather mysterious since the redirect/fancybox line comes after the server call and it doesn't fail to run, even if it runs wrong.
function ValidFatningCheck(){
var requestUrl = '/Tools.ashx?command=validscreen';
var req = new XMLHttpRequest();
req.open('GET', requestUrl, false);
req.send(null);
var res = "";
if (req.readyState==4)
res = req.responseText;
if(res == "true")
return true;
return false;
}
UPDATE : Problem solved by adding a timestamp to my XMLHttpRequest as multiple replies suggested. I didn't realize XMLHttpRequest uses AJAX so I overlooked it as a probable cause to the problem.
(I put in comments but will make this an answer now as it appears to have solved the problem) get requests are cached by IE but when the developer console is open it does not perform this cache.
three ways to fix:
add a timestamp to the request to trick the browser into thinking it is making a new request each time
var requestUrl = '/Tools.ashx?command=validscreen&time='+new Date().getTime();
set the response header to no-cache
make a POST request as these are not cached
(as pointed out by #juanmendes not ideal you are not editing a resource)

"undefined" randomly appended in 1% of requested urls on my website since 12 june 2012

Since 12 june 2012 11:20 TU, I see very weirds errors in my varnish/apache logs.
Sometimes, when a user has requested one page, several seconds later I see a similar request but the all string after the last / in the url has been replaced by "undefined".
Example:
http://example.com/foo/bar triggers a http://example.com/foo/undefined request.
Of course theses "undefined" pages does not exist and my 404 page is returned instead (which is a custom page with a standard layout, not a classic apache 404)
This happens with any pages (from the homepage to the deepest)
with various browsers, (mostly Chrome 19, but also firefox 3.5 to 12, IE 8/9...) but only 1% of the trafic.
The headers sent by these request are classic headers (and there is no ajax headers).
For a given ip, this seems occur randomly: sometimes at the first page visited, sometimes on a random page during the visit, sometimes several pages during the visit...
Of course it looks like a javascript problem (I'm using jquery 1.7.2 hosted by google), but I've absolutely nothing changed in the js/html or the server configuration since several days and I never saw this kind of error before. And of course, there is no such links in the html.
I also noticed some interesting facts:
the undefined requests are never found as referer of another pages, but instead the "real" pages were used as referer for the following request of the same IP (the user has the ability to use the classic menu on the 404 page)
I did not see any trace of these pages in Google Analytics, so I assume no javascript has been executed (tracker exists on all pages including 404)
nobody has contacted us about this, even when I invoked the problem in the social networks of the website
most of the users continue the visit after that
All theses facts make me think the problem occurs silently in the browers, probably triggered by a buggy add-on, antivirus, a browser bar or a crappy manufacturer soft integrated in browsers updated yesterday (but I didn't find any add-on released yesterday for chrome, firefox and IE).
Is anyone here has noticed the same issue, or have a more complete explanation?
There is no simple straight answer.
You are going to have to debug this and it is probably JavaScript due to the 'undefined' word in the URL. However it doesn't have to be AJAX, it could be JavaScript creating any URL that is automatically resolved by the browser (e.g. JavaScript that sets the src attribute on an image tag, setting a css-image attribute, etc). I use Firefox with Firebug installed most of the time, so my directions will be with that in mind.
Firebug Initial Setup
Skip this if you already know how to use Firebug.
After the installs and restarting Firefox for Firebug, you are going to have to enable most of Firebug's 'panels'. To open Firebug there will be a little fire bug/insect looking thing in the top right corner of your browser or you can press F12. Click through the Firebug tabs 'Console', 'Script', 'Net' and enable them by opening them up and reading the panel's information. You might have to refresh the page to get them working properly.
Debugging User Interaction
Navigate to one of the pages that has the issue with Firebug open and the Net panel active. In the Net panel there will be a few options: 'Clear', 'Persist', 'All', 'Html', etc. Make sure ALL is selected. Don't do anything on the page and try not to mouse over anything on it. Look through the requests. The request for the invalid URL will be red and probably have a status of 404 Not Found (or similar).
See it on load? Skip to the next part.
Don't see it on initial load? Start using your page and continue here.
Start clicking on every feature, mouse over everything, etc. Keep your eyes on the Net panel and watch for a requests that fail. You might have to be creative, but continue using your application till you see your browser make an invalid request. If the page makes many requests, feel free to hit the 'Clear' button on the top left of the Net panel to clear it up a bit.
If you submit the page and see a failed request go out really quick but then lose it because the next page loads, enable persistence by clicking 'Persist' in the top left of the Net panel.
Once it does, and it should, consider what you did to make that happen. See if you can make it happen again. After you figure out what user interaction is making it happen, dive into that code and start looking for things that are making invalid requests.
You can use the Script tab to setup breakpoints in your JavaScript and step through them. Investigate event handlers done via $(elemment).bind/click/focus/etc or from old school event attributes like onclick=""/onfocus="" etc.
If the request is happening as soon as the page loads
This is going to be a little harder to peg down. You will need to go to the Script tab and start adding break points to every script that runs on load. You do this by clicking on the left side of the line of JavaScript.
Reload your page and your break points should stop the browser from loading the page. Press the 'Continue' button on the script panel. Go to your net panel and see if your request was made, continue till it is found. You can use this to narrow down where the request is being made from by slowly adding more and more break points and then stepping into and out of functions.
What you are looking for in your code
Something that is similar to the following:
var url = workingUrl + someObject['someProperty'];
var url = workingUrl + someObject.someProperty;
Keep in mind that someObject might be an object {}, an array [], or any of the internal browser types. The point is that a property will be accessed that doesn't exist.
I don't see any 404/red requests
Then whatever is causing it isn't being triggered by your tests. Try using more things. The point is you should be able to make the request happen somehow. You just don't know yet. It has to show up in the Net panel. The only time it won't is when you aren't doing whatever triggers it.
Conclusion
There is no super easy way to peg down what exactly is going on. However using the methods I outlined you should be at least be able to get close. It is probably something you aren't even considering.
Based on this post, I reverse-engineered the "Complitly" Chrome Plugin/malware, and found that this extension is injecting an "improved autocomplete" feature that was throwing "undefined" requests at every site that has a input text field with NAME or ID of "search", "q" and many others.
I found also that the enable.js file (one of complitly files) were checking a global variable called "suggestmeyes_loaded" to see if it's already loaded (like a Singleton). So, setting this variable to false disables the plugin.
To disable the malware and stop "undefined" requests, apply this to every page with a search field on your site:
<script type="text/javascript">
window.suggestmeyes_loaded = true;
</script>
This malware also redirects your users to a "searchcompletion.com" site, sometimes showing competitors ADS. So, it should be taken seriously.
You have correctly established that the undefined relates to a JavaScript problem and if your site users haven't complained about seeing error pages, you could check the following.
If JavaScript is used to set or change image locations, it sometimes happens that an undefined makes its way into the URI.
When that happens, the browser will happily try to load the image (no AJAX headers), but it will leave hints: it sets a particular Accept: header; instead of text/html, text/xml, ... it will use image/jpeg, image/png, ....
Once such a header is confirmed, you have narrowed down the problem to images only. Finding the root cause will possibly take some time though :)
Update
To help debugging you could override $.fn.attr() and invoke the debugger when something is being assigned to undefined. Something like this:
​(function($, undefined) {
var $attr = $.fn.attr;
$.fn.attr = function(attributeName, value) {
var v = attributeName === 'src' ? value : attributeName.src;
if (v === 'undefined') {
alert("Setting src to undefined");
}
return $attr(attributeName, value);
}
}(jQuery));
Some facts that have been established, especially in this thread: http://productforums.google.com/forum/#!msg/chrome/G1snYHaHSOc/p8RLCohxz2kJ
it happens on pages that have no javascript at all.
this proves that it is not an on-page programming error
the user is unaware of the issue and continues to browse quite happily.
it happens a few seconds after the person visits the page.
it doesn't happen to everybody.
happens on multiple browsers (Chrome, IE, Firefox, Mobile Safari, Opera)
happens on multiple operating systems (Linux, Android, NT)
happens on multiple web servers (IIS, Nginx, Apache)
I have one case of googlebot following the link and claiming the same referrer. They may just be trying to be clever and the browser communicated it to the mothership who then set out a bot to investigate.
I am fairly convinced by the proposal that it is caused by plugins. Complitly is one, but that doesn't support Opera. There many be others.
Though the mobile browsers weigh against the plugin theory.
Sysadmins have reported a major drop off by adding some javascript on the page to trick Complitly into thinking it is already initialized.
Here's my solution for nginx:
location ~ undefined/?$ {
return 204;
}
This returns "yeah okay, but no content for you".
If you are on website.com/some/page and you (somehow) navigate to website.com/some/page/undefined the browser will show the URL as changed but will not even do a page reload. The previous page will stay as it was in the window.
If for some reason this is something experienced by users then they will have a clean noop experience and it will not disturb whatever they were doing.
This sounds like a race condition where a variable is not getting properly initialized before getting used. Considering this is not an AJAX issue according to your comments, there will be a couple of ways of figuring this out, listed below.
Hookup a Javascript exception Logger: this will help you catch just about all random javascript exceptions in your log. Most of the time programmatic errors will bubble up here. Put it before any scripts. You will need to catch these on the server and print them to your logs for analysis later. This is your first line of defense. Here is an example:
window.onerror = function(m,f,l) {
var e = window.encodeURIComponent;
new Image().src = "/jslog?msg=" + e(m) + "&filename=" + e(f) + "&line=" + e(l) + "&url=" + e(window.location.href);
};
Search for window.location: for each of these instances you should add logging or check for undefined concats/appenders to your window.location. For example:
function myCode(loc) {
// window.location.href = loc; // old
typeof loc === 'undefined' && window.onerror(...); //new
window.location.href = loc; //new
}
or the slightly cleaner:
window.setLocation = function(url) {
/undefined/.test(url) ?
window.onerror(...) : window.location.href = url;
}
function myCode(loc) {
//window.location.href = loc; //old
window.setLocation(loc); //new
}
If you are interested in getting stacktraces at this stage take a look at: https://github.com/eriwen/javascript-stacktrace
Grab all unhandled undefined links: Besides window.location The only thing left are the DOM links themselves. The third step is to check all unhandeled DOM links for your invalid URL pattern (you can attach this right after jQuery finishes loading, earlier better):
$("body").on("click", "a[href$='undefined']", function() {
window.onerror('Bad link: ' + $(this).html()); //alert home base
});
Hope this is helpful. Happy debugging.
I'm wondering if this might be an adblocker issue. When I search through the logs by IP address it appears that every request by a particular user to /folder/page.html is followed by a request to /folder/undefined
I don't know if this helps, but my website is replacing one particular *.webp image file with undefined after it's loaded in multiple browsers. Is your site hosting webp images?
I had a similar problem (but with /null 404 errors in the console) that #andrew-martinez's answer helped me to resolve.
Turns out that I was using img tags with an empty src field:
<img src="" alt="My image" data-src="/images/my-image.jpg">
My idea was to prevent browser from loading the image at page load to manually load later by setting the src attribute from the data-src attribute with javascript (lazy loading). But when combined with iDangerous Swiper, that method caused the error.

how to cancel http request using javascript

i have a page on which there an event handler attached to an onclick event. when the event fires it passes contents of a textbox to a GET request. since the url is not in the same domain so i create a script tag and and attach the url to its source like this
elem.onclick=fire;
function fire()
{
var text=document.getElementById('text').value;
var script=document.createElement("script");
script.className="temp";
script.src="some url"+"?param="+text;
document.body.appendChild(script);
}
now if that event is fired and more than one time i want to cancel all the previous GET request(because they still might be receiving response) and make the GET request with latest text. But for this i need to cancel the previous requests.
i tried
document.body.removeChild(script);
script.src=null;
but this does not work in Firefox(i am using Firefox 5) although this works in Google Chrome.Does anyone know if these requests can be cancelled in Firefox and if yes then how?
UPDATE
As suggested by Alfred, i used window.stop to cancel a request but does not cancel a request but hangs it up. It means that when i look into firebug it looks like the request is being made but there is no response.
The solution is simple: for creating HTTP requests, use <img> instead of <script> element. Also you always have to change the src attribute of the same element.
var img;
function fire()
{
var text = document.getElementById('text').value;
var im = img || (img = new Image());
im.src = "url"+"?param="+text;
}
You may ascertain that it actually works by doing the following: the URL you request should have a huge response time (you can ensure this using e.g. PHP's sleep function). Then, open Net tab in Firebug. If you click the button multiple times, you'll see that all incomplete requests are aborted.
This is entirely shooting from the hip, but if the script tag has not finished loading you can probably simply script.parentElement.removeChild( script ). That is more or less what mootools does anyway. (Technically, they replace /\s+/ with ' ' first, but that does not seem to be terribly important).
Would it be ok for you to use a JS framework? If so, MooTools has this functionality built into its Request.JSONP object
I'm not sure if this is what you're looking for, but it seems like a similar issue:
http://www.velocityreviews.com/forums/t506018-how-to-cancel-http-request-from-javascript.html
To get around the cross-domain issue, you might be able to use CORS instead (assuming you can change what's on the server):
http://hacks.mozilla.org/2009/07/cross-site-xmlhttprequest-with-cors/
If you do this, you could then use the more standard XMLHttpRequest's abort() function.
CORS is compatible with all the major modern browsers except Opera (http://caniuse.com/cors).

Creating a tweet button without opening a new window

I'm looking to add a "tweet this" button to a site. Simple enough, right? The catch is that the site is meant to run on an embedded platform that doesn't particularly handle popup windows, so I'm trying to do everything inside the page.
I'm able to successfully create my tweet button, attach an onClick handler to it, and construct a proper twitter.com/share URL for the relevant content. All works fine when I open that URL in a new window with window.open. However, if I try to open the URL in an iframe, nothing loads inside the frame. Even loading http://twitter.com into the iframe fails in the same way. However, loading Google or any other website seems to work just fine.
Any thoughts on what I'm missing here? Thanks! --zach
Edit:
Yep, they are detecting the iframe on load and blanking the page:
if (window.top !== window.self) {
document.write = "";
window.top.location = window.self.location;
setTimeout(function(){ document.body.innerHTML='';},1);
window.self.onload=function(evt){document.body.innerHTML='';};
}
Any reasonable way to get around this, or am I stuck writing my own auth pipeline through oauth? I don't need anything from their API, just letting users tweet to their own accounts.
Twitter (like Stack Overflow) is probably using some Javascript to ensure they're not being presented in an iFrame:
if(top!=self){
//hates you
}
I ran into something similar recently, and ended up re-doing part of my app without the iFrame element.
Go and get a developper account on twitter and things are made easy for you :)
Can you simply redirect the the twitter share URL? I'm guessing they want to be careful about opening the window in iframe's to prevent malicious sites from tweeting in a user's account without giving the user a chance to first confirm their intent to send this tweet.
You said window.open worked fine for popping up the url in a new window but have you tried popping it into the parent frame?
twtWindow=window.open([url],'_parent',[specs])
#yuval Unfortunately for you, the twitter url goes to a page that has the X-FRAME-OPTIONS:SAMEORIGIN header set in the response. It's not a Javascript check. The browser will simply refuse to render the page after seeing the header. This is done to prevent a clickjacking attack, usually done to steal a user's password.
So your only other option is really to redirect your current page with window.location.href=url.

how would you debug this javascript problem?

I've been travelling and developing for the past few weeks.
The site I'm developing was running well.
Then, the other day, i connected to a network and the page 'looked' fine, but it turns out the javascript wasn't running. I checked firebug, and there were no errors, as I was suspecting that maybe a script didn't load (I'm using the google api for jQuery and jQuery UI, as well as loading google maps api and fbconnect).
I would suspect that if the issue was with one of these pages not loading I would get an error, and yet there was nothing.
Thinking maybe i didn't connect properly or something, i reconnected to the network and even restarted my computer, as well as trying to run the local version. I got nothing.
The local version not running also hinted to me that it was the loading of an external javascript which caused the problem.
I let it pass as something strange with that one network. Unfortunately now I'm 100s of miles away.
Today my brother sent me an e-mail that the network he was on at the airport wouldn't load my page. Same issue. Everything is laid out properly, and part of the layout is set in Javascript, so clearly javascript is running.
he too got no errors. Of course, he got on his plane, and now he is no longer at the airport. Now the site works on his computer (and i haven't changed anything).
How on earth would you go about figuring out what happened in this situation? That is two of maybe 12 or so networks. But I have no idea how i would find a network that doesn't work (and living in a small town, it could be difficult for me to find a network that doesn't work).
Any ideas?
The site is still in Dev, so I'd rather not post a link just yet (but could in a few days).
What I can see not working is the javascript functions which are called on load, and on click. So i do think it is a javascript issue, but no errors.
This wouldn't be as HUGE an issue if I could find and sit on one of these networks, but I can't. So what would you do?
EDIT ----------------------------------------------------------
the first function(s - their linked) that doesn't get called is below.
I've cut the code of at the .ajax call as the call wasn't being made.
function getResultsFromForm(){
jQuery('form#filterList input.button').hide();
var searchAddress=jQuery('form#filterList input#searchTxt').val();
if(searchAddress=='' || searchAddress=='<?php echo $searchLocation; ?>'){
mapShow(20, -40, 0, 'areaMap', 2);
jQuery('form#filterList input.button').show();
return;
}
if (GBrowserIsCompatible()) {
var geo = new GClientGeocoder();
geo.setBaseCountryCode(cl.address.country);
geo.getLocations(searchAddress, function (result)
{
if(!result.Placemark && searchAddress!='<?php echo $searchLocation; ?>'){
jQuery('span#addressNotFound').text('<?php echo $addressNotFound; ?>').slideDown('slow');
jQuery('form#filterList input.button').show();
} else {
jQuery('span#addressNotFound').slideUp('slow').empty();
jQuery('span#headerLocal').text(searchAddress);
var date = new Date();
date.setTime(date.getTime() + (8 * 24 * 60 * 60 * 1000));
jQuery.cookie('address', searchAddress, { expires: date});
var accuracy= result.Placemark[0].AddressDetails.Accuracy;
var lat = result.Placemark[0].Point.coordinates[1];
var long = result.Placemark[0].Point.coordinates[0];
lat=parseFloat(lat);
long=parseFloat(long);
var getTab=jQuery('div#tabs div#active').attr('class');
jQuery('div#tabs').show();
loadForecast(lat, long, getTab, 'true', 0);
var zoom=zoomLevel();
mapShow(lat, long, accuracy, 'areaMap', zoom );
}
});
}
}
function zoomLevel(){
var zoomarray= new Array();
zoomarray=jQuery('span.viewDist').attr('id');
zoomarray=zoomarray.split("-");
var zoom=zoomarray[1];
if(zoom==''){
zoom=5;
}
zoom=parseFloat(zoom);
return(zoom);
}
function loadForecast(lat, long, type, loadForecast, page){
jQuery('div#holdForecast').empty();
var date = new Date();
var d = date.getDate();
var day = (d < 10) ? '0' + d : d;
var m = date.getMonth() + 1;
var month = (m < 10) ? '0' + m : m;
var year='2009';
toDate=year+'-'+month+'-'+day;
var genre=jQuery('span.genreblock span#updateGenre').html();
var numDays='';
var numResults='';
var range=jQuery('span.viewDist').attr('id');
var dateRange = jQuery('.updateDate').attr('id');
jQuery('div#holdShows ul.showList').html('<li class="show"><div class="showData"><center><img src="../hwImages/loading.gif"/></center></div></li>');
jQuery('div#holdShows ul.'+type+'List').livequery(function(){
jQuery.ajax({
type: "GET",
url: "processes/formatShows.php",
data: "output=&genre="+genre+"&numResults="+numResults+"&date="+toDate+"&dateRange="+dateRange+"&range="+range+"&lat="+lat+"&long="+long+'&page='+page,
success: function(response){
EDIT 2 -----------------------------------------------------------------------------
Please keep in mind that the problem is not that I can't load the site, the site works fine on most connections, but there are times when the site doesn't work, and no errors are thrown, and nothing changes. My brother couldn't run it earlier today while I had no problems, so it was something to do with his location/network. HOWEVER, the page loads, he had a connection, it was his first time visiting the site, so nothing could have been cashed. Same with when I had the issue a few days before. I didn't change anything, and I got to a different network and everything worked fine.
Two things: first -- get the javascript local to your site when developing. Loading it from elsewhere to take advantage of caching is an optimization that I'd leave to the end. I'd also only load it from highly available remote sites, like Google, to minimize problems. Second, make your site at least minimally usable without javascript enabled. Use form postbacks that get replaced with Ajax functionality from javascript that runs when the page is loaded, for example. You might not be able to get everything, but I've found that I can make most things work without javascript in at least a workable, if not elegant fashion.
I realize this doesn't solve your immediate problem, but I think it would help your site to remain available in the face of situations like this.
Turns out the problem with this was in assuming that google map could find any lat/long within north america reliably via ip address.
I add a if(!google.loader.ClientLocation) function for the instances where google cannot find the location via ip.
The strangest bit was that I was hitting this error in an office in downtown Palo Alto which I thought would have been heavily mapped by the google geocoder.
If some of the JS is being hosted by a different server (eg: if you are including something like jQuery from the jQuery site instead of hosting a copy of it yourself) then maybe one of these sites is down temporarily.
You could try use something like "Live HTTP Headers" (available at the Mozilla Addons site) to watch HTTP headers in real-time, which can be really useful when doing web development. You should be able to determine very quickly if all your JS is in fact loading correctly or not.
You could also use something like Ethereal or Wireshark, but that is probably a little heavy-handed when all you need is to see the request/response headers. Using an Addon is far less hassle.
A few things:
1.) where you include your scripts... make sure you have a separate closing tag! DO NOT self close them.
<script src="..."/><!--self-closing will fail, -->
<script src="..."></script><!--this will work -->
2.) is there a reason why you are using jQuery() rather than $() ?
3.) does your SERVER specify a DOCTYPE that your local environment didn't?
4.) what browser are you testing in? in particular are you testing in IE, if so does it work in Firefox?
5.) can you post some of the generated code if you can't supply a URL?
Once you're sure that all the scripts are loading as expected in the dev environment you could try either removing them one-by-one from the page and see which one recreates the issue you were having - then that's the script that wasn't loading.
Firebug has a Net Tab which does something very similar to what Live HTTP Headers does, even tracking the timings of the load and any ajax requests.
I almost always recommend Firefox plugin, "Firebug" for this.
Firstly, you can inspect the scripts to check that they have loaded, which will rule out the "it didn't load from a remote source" problem.
Secondly, it will display errors that occur in the JavaScript console, which may point out something that appeared to be silently previously.
Lastly, keep an eye out for cross-site-scripting problems when using JavaScript from another domain.

Categories