I am writing a diagnostic (greasemonkey) script for a very specific purpose, so I understand it may look odd. What I want to achieve is to display js and css info in a popup on a page so that it will show details that I can then use to troubleshoot/diagnose "our" products.
The following function is part of that script, and it builds a string (msg) which will be displayed in a popup window once all files have been diagnosed. This is working fine.
What I fail to understand is that towards the end of the code, I can "alert" the value (in this case, a line containing "Version"), yet I can't add that same value to the msg string that will be output later (and it will be displayed, including the closing ).
// get linked stylesheets
links = document.getElementsByTagName('link');
msg += '<h2>External Stylesheets</h2>';
for (var j in links) {
if (links[j].rel == "stylesheet") {
msg += "<div class='css" + [j] + "'>Stylesheet: " + "<a href=" + links[j].href + ">" + links[j].href + "</a>";
var styleSheet = links[j].href;
jQuery.get(links[j].href, function(data) {
lines = data.split("\n");
for (var k in lines) {
if ((lines[k]).search(/Version/) != -1) {
alert (lines[k]);
msg += " - " + lines[k];
break;
}
}
});
msg += "</div>";
}
}
I hope I made myself clear, I have a coding background, yet fairly new with the intricacies of Javascript/jQuery (that I added to the mix).
Edited: added a solution.
The asynchronous Ajax comments lead me to the solution (via the jQuery doc for jQuery.ajaxSetup), thanks everyone for your contribution, I learnt a lot.
First I tried:
jQuery.ajax({
url: links[j].href,
success: function(data) {
lines = data.split("\n");
for (var k in lines) {
if ((lines[k]).search(/Version/) != -1) {
msg += " - " + lines[k];
break;
}
}
},
asynch: false
});
which for some reason did not work either, so I reverted back to my initial code (using jQuery.get) but added the following line at the beginning of the script:
jQuery.ajaxSetup({async:false});
and it's working as expected now with the code I already had.