jQuery Script Not Running in IE7 - javascript

The following code works fine in every other browser except IE7. In fact, with this enabled on the page no scripts will work until I have commented it out.
$(document).ready(function () {
var pathname = $(location).attr('href');
if(pathname.indexOf('sess') === -1){
var path = pathname;
}else{
var path = pathname.replace(/sess[^&]*&?/, "");
}
$.ajax({
type: "POST",
url: "ajax/save_page.php",
data: 'last_page='+path
});
});
I have checked for errant commas and can't find any. If I pass a literal value through the Ajax call and comment out the rest of the function everything begins to work as it should but I need the whole function to work.

Ok, I'm beginning to realise that it isn't going to work on IE7 but I need the script to carry on working as it is without excluding IE7 users completely so I used..
if(navigator.appVersion.indexOf("MSIE 7.")!=-1)
to determine if the browser is IE7 and if so exclude that bit of script. Hopefully the user will be able to persuade their admin to upgrade them to a different browser when they realise that it isn't working as well as it could.
But, for the record, I agree that in an ideal world we shouldn't be supporting IE7 etc but in the real world a lot of people still use it and a lot can't do anything about it. I work within the medical and dental industries and a lot of hospitals etc (about 50%) are still using XP with IE7 with no immediate plans for upgrading despite knowing that XP is no longer supported by Microsoft.
Revision to solution
Ok, I have revised my solution, I am using php sessions now for passing around the sess variable that was previously in the url so I no longer have to try and take it out of the url whilst leaving the rest of the params intact.
So now I am using
var path = window.location.href;
$.ajax({
type: "POST",
url: "ajax/save_page.php",
data: 'last_page='+path
});
Which works fine in all of the browsers I am testing it in including IE7

Related

Odd Javascript behavior - porting to WordPress

I'm currently making my first effort into porting a webpage to Wordpress, so forgive my inexperience on the subject.
In my page, I have the following code:
function workLoad() {
$.ajaxSetup({ cache: false });
$('.thumb-unit').click(function() {
var $this = $(this),
newTitle = $this.find('strong').text(),
newFolder = $this.data('folder'),
spinner = 'Loading...',
newHTML = 'work/'+ newFolder +'.html';
$('.project-load').html(spinner).load(newHTML);
$('.project-title').text(newTitle);
});
}
In the past, this has worked fine hosted both locally and on Github. However, running my wordpress build locally through MAMP gives me the following error:
jquery-2.1.1.min.js:4 GET http://localhost/work/proj-1.html?_=1485348127113 404 (Not Found)
The URL should be fine, except for the part where it adds the ?_=(number). I'm not familiar with this behavior or what causes it. I tried changing work/ to /work/, since the dir is in the root folder, but that didn't solve it. I also have tried changing the variable to
newHTML = '< ?php bloginfo('template_directory')' + '/work/'+ newFolder +'.html';without the space after the opening bracket but to no avail. I also tried putting that bit in its own var, but it keeps adding ?_=1485348127113 to the URL of the html file I want to load, resulting in a 404 error.
What causes this? Thanks in advance for any advice you could share.
This timestamp is added for You to obtain the latest version of the file using ajax load.
If You want to disable this behaviour, You should set
$.ajaxSetup({
cache: true
});
This will enable caching and Your request would not contain the ?_=1485348127113 part anymore. This parameter should not cause the 404 not found error. Please check your path.

YQL Request in IE8

I've been struggling to get this to work for a while. Basically I want to get information from Yahoo via the YQL resource. I have it working for all browsers except IE. (IE8 is the only one I've tested, but it's a must).
A fiddle here.
$.ajax({
type: 'GET',
dataType: 'jsonp',
crossDomain: true,
url: 'http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%3D%22http%3A%2F%2Ffinance.yahoo.com%2Fwebservice%2Fv1%2Fsymbols%2Fyhoo%2Fquote%3Fformat%3Djson%22%20and%20itemPath%20%3D%20%22list.resources.resource.fields%22&format=xml&callback=?',
success: function(data) {
console.log(data);
name = $($(data.results[0]).find('name')[0]).text();
symbol = $($(data.results[0]).find('symbol')[0]).text();
price = $($(data.results[0]).find('price')[0]).text();
price = parseInt(price);
$('body').append(name + '; ' + symbol + '; ' + price);
}
});
The YQL request (for the console):
select * from json where url="http://finance.yahoo.com/webservice/v1/symbols/yhoo/quote?format=json" and itemPath = "list.resources.resource.fields"
It's a simple Ajax get call, but I can't seem to get access for IE8 to do anything with the data. (The return dataType that you see in the URL doesn't matter-- I've tried it with both XML and JSON). Am I missing something? Or is this even possible?
In your example you are using jQuery-2.0.2 but since jQuery-2.0 it dropped the support for IE-6/7/8. From jQuery 2.0 Released | Official jQuery Blog :
No more support for IE 6/7/8: Remember that this can also affect IE9
and even IE10 if they are used in their “Compatibility View” modes
that emulate older versions. To prevent these newer IE versions from
slipping back into prehistoric modes, we suggest you always use an
X-UA-Compatible tag or HTTP header. If you can use the HTTP header it
is slightly better for performance because it avoids a potential
browser parser restart.
Here is a working fiddle using jQuery-1.9.1.

IE 8 (ONLY) crashes with JavaScript / jQuery calls to plugins

I'm in need of some help.
I'm building a team bio page it keeps crashing IE8 when I call jQuery plugins.
I'm not sure what is going on and can't even run the IE debugger because it crashes so hard.
Any IE8 / jQuery experts out there willing to take a look and offer some help?
Here is the main team page. Clicking through to any of the links causes the crash in IE8.
I am using:
jQuery Tagsphere, AnythingSlider, and jQuery Cycle.
Thanks in advance for any insight into this.
I had a similar problem, most notably closing iframes with IE8. Stumbled across the following code in jquery-1.6.2, which was intended to solve problems with document.domain. Some comments on the web lead me to believe this was a recent problem. Dropped back to jquery-1.4.4 and the problem was resolved.
CODE SEGMENT FROM JQUERY-1.6.2 FOLLOWS:
// #8138, IE may throw an exception when accessing
// a field from window.location if document.domain has been set
try {
ajaxLocation = location.href;
} catch( e ) {
// Use the href attribute of an A element
// since IE will modify it given document.location
ajaxLocation = document.createElement( "a" );
ajaxLocation.href = "";
ajaxLocation = ajaxLocation.href;
}

Jquery - how to load everything except the images?

I'm currently working on a WordPress addition which loads full post content (normally it shows exceprts) when asked to. I did my code like this:
$(".readMore").click(function() {
var url = $(this).attr("href");
$(this).parent("p").parent("div").children("div.text").slideUp("slow", function () {
$(this).load(url + " .text", function(){
$(this).slideDown("slow");
});
});
$(this).parent("p").fadeOut();
return false; });
And it works. But I don't want images to be loaded. I tried .text:not(img), but it didn't worked. How can I do this?
The trick, of course, is preventing the images from being downloaded unnecessarily by the user's browser; not displaying them is easy.
I only have two browsers were it's easy and convenient to tell what's downloading: Chrome and Firefox+Firebug. In my tests, Martin's solution using *:not(img) results in the images being downloaded (although not displayed) in both Chrome and Firefox+Firebug. (I emphasize "Firefox+Firebug" because Firebug can change the behavior of Firefox on occasion, and so it may well be changing its behavior here, although I don't think it is; more on that below.)
It took some tweaking, but this seems to do the trick (more on testing below):
$.ajax({
url: url,
success: function(data) {
var div = $("<div>").html(data);
if (stripImages) {
// Find the images, remove them, and explicitly
// clear the `src` property from each of them
div.find("img").remove().each(function() {
this.src = "";
});
}
$(targetSelector).append(div.children());
},
error: function(jxhr, status, err) {
display("ajax error, status = " + status + ", err = " + err);
}
});
Live example The "Include big image" checkbox includes a large file from NASA's Astronomy Picture of the Day (APOD).
The key there was setting the src of the img elements to "". On Chrome, just removing the elements was enough to prevent Chrome starting the download of the images, but on Firefox+Firebug it not only started downloading them, but continued even when the download took considerable time. Clearing the src causes Firefox to abort the download (I can see this in the Firebug Net console).
So what about IE? Or Firefox without Firebug? I only did unscientific testing of those, but it's promising: If I run my live example of Martin's solution on either IE or Firefox without Firebug in a VM, I see the VM's network interface working hard, suggesting that it's downloading that big APOD picture. In contrast, if I run my solution above in that same environment (with caches cleared, etc., etc.), I don't see the VM network interface doing that work, suggesting that the download is either not being started or is being aborted early on.
.text *:not(img) will select every descendant from .text that is not an image, so in theory it should work.

What other options for replacing entire HTML document via W3C DOM?

I am curious about people's experiences with replacing the entire document at runtime in an Ajax web app. It's rare, but I've found a few situations where the app requires an entire page rebuild and everything is present locally without needing another server round-trip.
I can easily prepare the new document as either a new DOM tree or as a String. So I'm evaluating the trade-offs for various approaches.
If I want to use the String approach this seems to work:
document.open();
document.write(newStringDoc);
document.close();
Most browsers do this just fine, but many have a slight flicker when re-rendering. I've noticed that on the 2nd time through Firefox 4.0b7 will just sit there and spin as if it is loading. Hitting the stop button on the location bar seems to complete the page render. (Edit: this appears to be fixed in 4.0b8) Also this method seems to prevent the user from hitting refresh to reload the current URL (it reloads the dynamically generated page).
If I use a new DOM tree approach (which has different advantages/disadvantages in flexibility and speed), then this seems to work:
document.replaceChild(newDomDoc, document.documentElement);
Most browsers seem to handle this perfectly fine without flicker. Unfortunately, IE9 beta throws "DOM Exception: HIERARCHY_REQUEST_ERR (3)" on replaceChild and never completes. I haven't tried the latest preview release to see if this is just a new bug that got fixed. (Edit: this appears to be fixed in RC1.)
My question: does anyone have a different approach than either of these? Does anyone have any other caveats where perhaps a particular browser fundamentally breaks down with one of these approaches?
Update: Perhaps this will add context and help the imagination. Consider a situation where an application is offline. There is no server available to redirect or refresh. The necessary state of the application is already loaded (or stored) client-side. The UI is constructed from client-side templates.
I believe that Gmail uses iframes embedded within a root document. It appears the starting document for at least some of these iframes are just a bare HTML5 document which the parent document then manipulates.
Using an iframe would be another variant on the requirement to replace the current document by replacing the entire child iframe or just its document. The same situation exists though of what approach to attach the new document to the iframe.
I guess I will answer this with my own findings as I'm wrapping up my research on this.
Since the two browsers which have issues with one of these methods are both beta, I've opened bug reports which hopefully will resolve those before their full release:
Firefox 4 Beta: https://bugzilla.mozilla.org/show_bug.cgi?id=615927
Edit: Fixed in FF 4b8.
Internet Explorer 9 Beta: https://connect.microsoft.com/IE/feedback/details/626473
Edit: Fixed in IE9 RC1.
I've also found pretty consistently that this...
document.replaceChild(newDomDoc, document.documentElement);
...is 2-10x faster than this...
var doc = document.open("text/html");
doc.write(newStringDoc);
doc.close();
...even when including the time needed to build the DOM nodes vs. build the HTML string. This might be the reason for the flicker, or perhaps just another supporting argument for the DOM approach. Chrome doesn't have any flicker with either method.
Note the subtle change of storing the returned document which circumvents the bug in Firefox 4.0b7.
Also note this added MIME type which the IE docs claim is "required".
Finally, Internet Explorer seems to have a bit of trouble resolving link tags that were built before the new document is swapped in. Assigning the link href back to itself appears to patch it up.
// IE requires link repair
if (document.createStyleSheet) {
var head = document.documentElement.firstChild;
while (head && (head.tagName||"") !== "HEAD") {
head = head.nextSibling;
}
if (head) {
var link = head.firstChild;
while (link) {
if ((link.tagName||"") === "LINK") {
link.href = link.href;
}
link = link.nextSibling;
}
}
}
One could cover all bases and combine them like this...
var doc = document;
try {
var newRoot = newDoc.toDOM();
doc.replaceChild(newRoot, doc.documentElement);
// IE requires link repair
if (doc.createStyleSheet) {
var head = newRoot.firstChild;
while (head && (head.tagName||"") !== "HEAD") {
head = head.nextSibling;
}
if (head) {
var link = head.firstChild;
while (link) {
if ((link.tagName||"") === "LINK") {
link.href = link.href;
}
link = link.nextSibling;
}
}
}
} catch (ex) {
doc = doc.open("text/html");
doc.write(newDoc.toString());
doc.close();
}
...assuming you have the ability to choose your approach like I do.

Categories

Resources