why is IE8 loading javascripts incompletely? - javascript

I'm running IE8 in normal mode (whatever it is when compatibility is NOT turned on) on WinXP. I'm doing maintenance on a rails app that was written a few years ago. Often when I load a page, and/or refresh a page, it reports different javascript errors. When I look at the errors in the Developer tool, it appears that a javascript file hasn't loaded completely. So the errors are frequently syntax related, such as '}' expected.

Trailing comma in object literal or array declaration? Some browsers accept this without error, IE does not.
// Trailing commas are bad
var someArray = [
"thing",
"last",
];
var someObject = {
one: "thing",
after: "another",
};
As galambalazs suggested in his comment, jslint will pick up problems like this for you.

Cntrl + F your javascript file and look for a rogue "return" statement.

I ran into this problem on older versions of IE. It was never reproducible in a test harness and left no trace in server logs, but consistently affected a very small percentage of IE 6 loads.
The solution was to have the embedding HTML file double check that the JS was loaded.
foo.js:
// do all the real work.
// As the last statement, set a variable indicating completion.
foo_js_fully_loaded = true;
foo.html:
<script src=foo.js></script>
<script>if (!foo_js_fully_loaded) { /* reload the page */ }</script>

Related

SCRIPT1014: Invalid Character Grave Accent (`) IE [duplicate]

Here's a new one, IE11 is throwing errors on code that works in every other browser.
Anyway, after a few hours of "fixing" code so that IE11 doesn't fall on its own face I have come across an error I just cannot seem to find a solution to. Here is the code in question:
$('input[name="messageAccount"]').change(function () {
$aButton.show();
var addedIds = $("#hdnfield").val();
if (addedIds == null || addedIds === "") {
$("#hdnfield").val(this.value);
} else {
$("#hdnfield").val(`${addedIds}${this.value}`);
};
});
This is nested on the inside of the success call in an Ajax request. IE's debugger is saying the error is coming from the content of the else statement but it's also reading all the brackets wrong. For example the opening parenthesis on this function is being "closed" after the closing bracket for the Ajax request... (hopefully that made sense).
Has anyone else had a similar issue with IE before? I've got a number of other bugs to fix so if there are any replies I will post back as soon as I can. Thanks in advance.
EDIT: just for reference I am currently running this locally and is part of what will become an internally hosted web app.
It's because "`" (template strings) is not supported by IE : http://caniuse.com/#search=string
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
See https://stackoverflow.com/a/27678299/2195875
To avoid this error you can either use a ES6 to ES5 transpiler, or just directly write valid ES5 javascript:
instead of
`string text ${expression} string text`
write
"string text "+expression+" string text"
You can also add polyfill to your html:
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-polyfill/6.26.0/polyfill.min.js"/>

Is <!-- valid javascript?

I recently had to fix a bug that manifested sometimes in Internet Explorer. The bug was that, sometimes, the parser choked on code like
<script type="text/javascript">
<!-- // comments -->
/*...*/
</script>
Which we fixed by correcting the comment.
My question is: is "<!--" valid javascript code, or not? I tried testing it with firebug, and it only says" Undefined". JSFiddle didn't faze. IE only choked on it some of the times (reloading the page in question would show up the result of the script involved).
While knowing that, for historical reasons, an HTML comment inside js could be valid depending on its exact position and the phase of the moon is indeed useful, I was more interested in answers like "var <!-- foo is valid js code, but <!-- on its own is not. Here's why:..."
I did some analysis in firebug:
var x = 2;
var y = 3;
var z = 0;
console.log(x);
console.log(y);
y<!--x;
console.log(x);
console.log(y);
z = y<! --x;
console.log(x);
console.log(y);
console.log(z);
resulting in the following:
2
3
2
3
1
3
false
The difference between the first and second tries is interesting.
I then tried
z = (y <!--x);
console.log(z);
Which failed with
SyntaxError: missing ) in parenthetical
First to answer your question on Is <!-- valid JavaScript: No, it is not, in none of the forms you gave in your question. This is because it is not valid according to the JavaScript BNF grammar which you can find here: http://tomcopeland.blogs.com/EcmaScript.html
If you are interested, here's why you do see it inside script blocks: It is the HTML comment character. You do see it very often within script tags like this:
<script>
<!--
.. JavaScript code...
// -->
</script>
The reason is that old browsers (and with "old" I mean "stone age" like Netscape 1.0) that do not even support JavaScript and would otherwise just show the code on the screen. By doing it this way those older browsers treat the JavaScript as HTML comments and do not show it. Newer browsers ignore this and just run the JavaScript.
This is how it actually works (from http://www.w3.org/TR/html401/interact/scripts.html#h-18.3.2): The JavaScript engine allows the string <!-- to occur at the start of a SCRIPT element, and ignores further characters until the end of the line. JavaScript interprets // as starting a comment extending to the end of the current line. This is needed to hide the string --> from the JavaScript parser.
Because all browsers nowadays support JavaScript (even if it is turned off) you do not need to do this anymore. It is actually bad practice to do so because of these reasons (from http://www.javascripttoolbox.com/bestpractices/#comments):
Within XHTML documents, the source will actually be hidden from all browsers and rendered useless
-- is not allowed within HTML comments, so any decrement operations in script are invalid
An even deeper explanation and all the cons and pro's can be found here: http://lachy.id.au/log/2005/05/script-comments
In older browsers, it was required to have these comments inserted because the browsers couldn't parse the javascript properly. it would try to literally parse the javascript as html which caused script execution failures.
Today, browsers don't need this.
It's not.
If you go to the standard, you'll see that a < can only exist in a RelationalExpression, which <!-- is not as it hasn't got anything on the left-hand side.
Comments in Javascript are like other C-type languages (// for single line, /* */ for blocks.

Razor/JavaScript and trailing semicolon

Using Visual Studio 2012, on a Razor view page, in the JavaScript section, I am getting what I think is a battle between Razor syntax vs JavaScript syntax. In particular, the trailing semicolon in the script section is flagged by intellisense and a compiler warning (not error) is delivered:
'Warning 13 Syntax error'.
If I remove it, then I get a statement termination recommendation (ReSharper in this case, but just good practice).
<script type="text/javascript">
$().ready(function(){
var customer = #Html.Raw(ViewBag.CustomerJSON); // <- Razor (I think) doesn't like this semicolon
});
</script>
Is this a bug in Razor? If so, is there a way I can rewrite this to avoid this issue?
Is this a bug in Razor?
Absolutely not. Run your application, and it will work as expected.
It is a bug in the tools you are using (Visual Studio 2012, ReSharper, ...) that are incapable of recognizing perfectly valid syntax and warning you about something that you shouldn't be warned about. You could try opening an issue on the Microsoft Connect site and signalling this bug if that hasn't already been done.
Since this still seems to be happening and it is a nuisance I figured I will at least let others know what I ended up using as a "hack". I don't want to ignore the warning and would rather accept a hokier syntax (and yes someone is going to say this will kill performance :))
What I use as a workaround is to use a client side addition at the end. For me this error occurred on defining an "integer" constant, so
window.foo = #(Model.Something);
gave me the good old semicolon error. I simply changed this to:
window.foo = #Model.Something + 0;
(In the stated questions case you should just be able to add '', so + ''.
I know there is a whole another addition happening on the client and it isn't elegant, but it does avoid the error. So use it or don't, but I prefer this over seeing the warning/error.
If someone knows of a server-side syntactical workaround for this I would prefer this to the client-side one, so please add.
I found that wrapping the Razor syntax in a JavaScript identity function also makes the IDE happy.
<script type="text/javascript">
#* I stands for Identity *#
function I(obj) { return obj; }
$().ready(function(){
var customer = I(#Html.Raw(ViewBag.CustomerJSON));
});
</script>
This worked for me:
var customer = #Html.Raw(ViewBag.CustomerJSON + ";")
Here's a workaround for booleans:
var myBool = #(Model.MyBool ? "true;" : "false;")
This worked for me
#Html.Raw(string.Format("var customer = {0};", ViewBag.CustomerJSON));
<script type="text/javascript">
$().ready(function(){
var customerName = ('#ViewBag.CustomerName'); // <- wrap in parens
});
</script>
Isn't it as simple as wrapping in parentheses? Putting values through the console seem to work fine with no side effect.
It works for strings, but it still gives the error for non-quoted values, but I still like this for string values. For numbers you could just use parseInt('#Model.TotalResultCount', 10).

IE Object doesn't support this property or method

This is probably the beginning of many questions to come.
I have finished building my site and I was using Firefox to view and test the site. I am now IE fixing and am stuck at the first JavaScript error which only IE seems to be throwing a hissy about.
I run the IE 8 JavaScript debugger and get this:
Object doesn't support this property or method app.js, line 1 character 1
Source of app.js (first 5 lines):
var menu = {};
menu.current = "";
menu.first = true;
menu.titleBase = "";
menu.init = function(){...
I have tested the site in a Webkit browser and it works fine in that.
What can I do to fix this? The site is pretty jQuery intensive so i have given up any hope for getting it to work in IE6 but I would appreciate it working in all the others.
UPDATE: I have upload the latest version of my site to http://www.frankychanyau.com
In IE8, your code is causing jQuery to fail on this line
$("title").text(title);
in the menu.updateTitle() function. Doing a bit of research (i.e. searching with Google), it seems that you might have to use document.title with IE.
Your issue is (probably) here:
menu.updateTitle = function(hash){
var title = menu.titleBase + ": " + $(hash).data("title");
$("title").text(title); // IE fails on setting title property
};
I can't be bothered to track down why jQuery's text() method fails here, but it does. In any case, it's much simpler to not use it. There is a title property of the document object that is the content of the document's title element. It isn't marked readonly, so to set its value you can simply assign a new one:
document.title = title;
and IE is happy with that.
It is a good idea to directly access DOM properties wherever possible and not use jQuery's equivalent methods. Property access is less troublesome and (very much) faster, usually with less code.
Well, your line 1 certainly looks straight forward enough. Assuming the error line and number is not erroneous, it makes me think there is a hidden character in the first spot of your js file that is throwing IE for a fit. Try opening the file in another text editor that may support display of normally hidden characters. Sometimes copying/pasting the source into a super-basic text-editor, like Notepad, can sometimes strip out non-displayable characters and then save it back into place directly from Notepad.

Possible cases for Javascript error: "Expected identifier, string or number"

Some users are reporting occasional JS errors on my site. The error message says "Expected identifier, string or number" and the line number is 423725915, which is just an arbitrary number and changes for each report when this occurs.
This mostly happens with IE7/ Mozilla 4.0 browsers.
I scanned my code a bunch of times and ran jslint but it didn't pick anything up - anyone know of the general type of JS problems that lead to this error message?
The cause of this type of error can often be a misplaced comma in an object or array definition:
var obj = {
id: 23,
name: "test", <--
}
If it appears at a random line, maybe it's part of an object defintion you are creating dynamically.
Using the word class as a key in a Javascript dictionary can also trigger the dreaded "Expected identifier, string or number" error because class is a reserved keyword in Internet Explorer.
BAD
{ class : 'overlay'} // ERROR: Expected identifier, string or number
GOOD
{'class': 'overlay'}
When using a reserved keyword as a key in a Javascript dictionary, enclose the key in quotes.
Hope this hint saves you a day of debugging hell.
Actually I got something like that on IE recently and it was related to JavaScript syntax "errors". I say error in quotes because it was fine everywhere but on IE. This was under IE6. The problem was related to JSON object creation and an extra comma, such as
{ one:1, two:2, three:3, }
IE6 really doesn't like that comma after 3. You might look for something like that, touchy little syntax formality issues.
Yeah, I thought the multi-million line number in my 25 line JavaScript was interesting too.
Good luck.
This is a definitive un-answer: eliminating a tempting-but-wrong answer to help others navigate toward correct answers.
It might seem like debugging would highlight the problem. However, the only browser the problem occurs in is IE, and in IE you can only debug code that was part of the original document. For dynamically added code, the debugger just shows the body element as the current instruction, and IE claims the error happened on a huge line number.
Here's a sample web page that will demonstrate this problem in IE:
<html>
<head>
<title>javascript debug test</title>
</head>
<body onload="attachScript();">
<script type="text/javascript">
function attachScript() {
var s = document.createElement("script");
s.setAttribute("type", "text/javascript");
document.body.appendChild(s);
s.text = "var a = document.getElementById('nonexistent'); alert(a.tagName);"
}
</script>
</body>
This yielded for me the following error:
Line: 54654408
Error: Object required
Just saw the bug in one of my applications, as a catch-all, remember to enclose the name of all javascript properties that are the same as keyword.
Found this bug after attending to a bug where an object such as:
var x = { class: 'myClass', function: 'myFunction'};
generated the error (class and function are keywords)
this was fixed by adding quotes
var x = { 'class': 'myClass', 'function': 'myFunction'};
I hope to save you some time
http://closure-compiler.appspot.com/home will pick this error up with an accurate reference to the actual line number in the offending script.
As noted previously, having an extra comma threw an error.
Also in IE 7.0, not having a semicolon at the end of a line caused an error. It works fine in Safari and Chrome (with no errors in console).
IE7 is much less forgiving than newer browsers, especially Chrome. I like to use JSLint to find these bugs. It will find these improperly placed commas, among other things. You will probably want to activate the option to ignore improper whitespace.
In addition to improperly placed commas, at this blog in the comments someone reported:
I've been hunting down an error that only said "Expected identifier"
only in IE (7). My research led me to this page. After some
frustration, it turned out that the problem that I used a reserved
word as a function name ("switch"). THe error wasn't clear and it
pointed to the wrong line number.
Remove the unwanted , sign in the function. you will get the solution.
Refer this
http://blog.favrik.com/2007/11/29/ie7-error-expected-identifier-string-or-number/
This error occurs when we add or missed to remove a comma at the end of array or in function code. It is necessary to observe the entire code of a web page for such error.
I got it in a Facebook app code while I was coding for a Facebook API.
<div id='fb-root'>
<script type='text/javascript' src='http://connect.facebook.net/en_US/all.js'</script>
<script type='text/javascript'>
window.fbAsyncInit = function() {
FB.init({appId:'".$appid."', status: true, cookie: true, xfbml: true});
FB.Canvas.setSize({ width: 800 , height: 860 , });
// ^ extra comma here
};
</script>
This sounds to me like a script that was pulled in with src, and loaded just halfway, causing a syntax error sine the remainder is not loaded.
IE7 has problems with arrays of objects
columns: [
{
field: "id",
header: "ID"
},
{
field: "name",
header: "Name" , /* this comma was the problem*/
},
...
Another variation of this bug: I had a function named 'continue' and since it's a reserved word it threw this error. I had to rename my function 'continueClick'
Maybe you've got an object having a method 'constructor' and try to invoke that one.
You may hit this problem while using Knockout JS. If you try setting class attribute like the example below it will fail:
<span data-bind="attr: { class: something() }"></span>
Escape the class string like this:
<span data-bind="attr: { 'class': something() }"></span>
My 2 cents.
I too had come across this issue. I found below two solutions.
1). Same as mentioned by others above, remove extra comma from JSON object.
2). Also, My JSP/HTML was having . Because of this it was triggering browser's old mode which was giving JS error for extra comma. When used it triggers browser's HTML5 mode(If supported) and it works fine even with Extra Comma just like any other browsers FF, Chrome etc.
Here is a easy technique to debug the problem:
echo out the script/code to the console.
Copy the code from the console into your IDE.
Most IDE's perform error checking on the code and highlight errors.
You should be able to see the error almost immediately in your JavaScript/HTML editor.
Had the same issue with a different configuration. This was in an angular factory definition, but I assume it could happen elsewhere as well:
angular.module("myModule").factory("myFactory", function(){
return
{
myMethod : function() // <--- error showing up here
{
// method definition
}
}
});
Fix is very exotic:
angular.module("myModule").factory("myFactory", function(){
return { // <--- notice the absence of the return line
myMethod : function()
{
// method definition
}
}
});
This can also happen in Typescript if you call a function in middle of nowhere inside a class. For example
class Dojo implements Sensei {
console.log('Hi'); // ERROR Identifier expected.
constructor(){}
}
Function calls, like console.log() must be inside functions. Not in the area where you should be declaring class fields.
Typescript for Windows issue
This works in IE, chrome, FF
export const OTP_CLOSE = { 'outcomeCode': 'OTP_CLOSE' };
This works in chrome, FF, Does not work in IE 11
export const OTP_CLOSE = { outcomeCode: 'OTP_CLOSE' };
I guess it somehow related to Windows reserved words

Categories

Resources