Syntax error in JS intended for website "flashing" fix - javascript

1 if (document.getElementById) {
2 document.write(
3 '<style type="text/css" media="screen">
4 #element1, .element2 {display:none;}
5 </style>'
6 );
7 }
I get "Uncaught SyntaxError: Unexpected token ILLEGAL" on line 3. This is probably soo easy for you guys, but I just started with JS and like always - it's a whole new language.
I could use 2 kinds of advice if they are different..
How to use this code in file.php between < script > tags?
How to use this code from seperate file.js file?
I know how to link .js, don't worry about that.
For the record, this is intended to be in < head > and to hide some html elements before they are fully loaded if Im not mistaken. Experts, feel free to confirm this or give me a better solution if there is any, thank you!

In JavaScript, strings cannot be broken up into multiple lines. The new line character is not a valid string character. You will have to close the string on each line and add the string concatenation operator after each line that is continued on the next line (or before each line that is a continuation of the previous line, like so:
if (document.getElementById)
{
document.write(
'<style type="text/css" media="screen">' +
'#element1, .element2 {display:none;}'
+ '</style>');
}
This will get rid of the error, but it will not achieve the desired effect of hiding elements. document.write automatically calls document.open() if an HTML document has already been opened (which it has, if the script is executing.) document.open will wipe out the contents of the page, including the script that contains that code. You will be left with a blank page.
As #Chris says, you can include script tags in the output of a php script simply by writing the script outside of the php parsing context. i.e.
?>
<head>
<!-- other stuff -->
<script type="text/javascript">// type="text/javascript" is only needed for browser versions that do not support HTML5
// place code here
</script>
<!-- other stuff -->
</head>
<?php
On the other hand, if you wish to include a separate, external JavaScript file, replace that script tag in the code snippet above with
<script src="[absolute or relative path to script]" type="text/javascript">
</script>
Note that script tags are not self-closing, so even though this script tag has no contents, you cannot use the self closing tag syntax, as in <script ... />
As for the problem of how to handle the flickering problem, this Stack Overflow post may be helpful:
Page Transitioning - Ways to Avoid the "flicker"

I'm not an expert on php, but this site says this is your basic syntax for embedded php.
http://php.net/manual/en/language.basic-syntax.phpmode.php
<p>This is going to be ignored by PHP and displayed by the browser.</p>
<?php echo 'While this is going to be parsed.'; ?>
<p>This will also be ignored by PHP and displayed by the browser.</p>
Also, it looks like you probably need to escape a few things for that tag.
'<style type=\"text/css\" media=\"screen\">
#element1, .element2 {display:none;}
</style>'

Related

Javascript weird logical operator behavior using JSF : `&&`

I am trying to work on a keydown event in javascript and I am currently stuck on something that never happened to me before :
var maxL = $("#myField").attr("maxLength")
console.log("Maximum Length : " + maxL);
if (e.key.length === 1 && str.length >= parseInt(maxL)) {
console.log(">>>> in if");
console.log(">>>> e.char == \"" + e.key + "\"");
e.preventDefault();
}
When I load the page, it fails. On debug, my server console logs this error :
Error Parsing /folder/myPage.xhtml: Error Traced[line: 384] The entity name
must immediately follow the '&' in the entity reference.
where 384 is the line where the if is
I tried both conditions individually and they work just fine, which leads me to think there is something wrong with the "&&" operator.
If this is of any importance, I work on a WebSphere server in JSF with PrimeFaces and I try to run it in Chrome. The javascript is embedded inside a div in order to delete it after the page is loaded :
<div id="deleteScript">
<SCRIPT>
//my script code
$("#deleteScript").remove();
</SCRIPT>
</div>
I actually had to use the following syntax :
<div id="deleteScript">
<SCRIPT>
<!--//--><![CDATA[//><!--
//my script code
$("#deleteScript").remove();
//--><!]]>
</SCRIPT>
</div>
Which I could find on this other answer. BalusC seems to think that we should only use this solution if we work for older web browsers, but it appears that it becomes necessary when we work on older JSF servers as well.
Looks like the jsf is interpreting parts of your js as if it was xhtml.
Wrap your script (after the <script> tag) with <![CDATA[ and ]]> to make it interpret the content literally:
<script>
<![CDATA[
//your code
]]>
</script>
The <![CDATA[ ... ]]> tags are used in XML files to allow the use of characters that usually are reserved such as '&', '>' etc. You can read more on this answer and here.
This is not a problem with the browser; It looks like your server is attempting to operate on the "&&". Maybe you have to escape it in your code.
The problem comes from the fact that you have your JS written in the html script tag. What I would do if I were you is:
<div id="deleteScript">
<script src="path/to/script.js"></script>
</div>
Since the script tag is within the div with ID "deleteScript", the element will exist when the script loads and you can delete it.

PhpStorm does not show syntax errors of JavaScript in .php files

I am using PhpStorm 10.0.3. I have test.php file. Inside this file I have some JavaScript. What I found is, if there are any JavaScript syntax errors it does not show.
For example:
image.setAttribute("data-src2", "example.com/1.jpg";
no syntax error is shown at the end in the test.php
The entire file is
<html>
<head></head>
<body>
<?php
$you = "sample";
?>
<script type="text/javascript">
//image or frame
var image = document.createElement("img");
image.setAttribute("data-src", "example.com");
image.setAttribute("data-src2", "example.com";
contentDiv.appendChild(image);
</script>
</body>
</html>
If I rename the file to text.html then JavaScript syntax error is shown:
image.setAttribute("data-src2", "example.com/1.jpg";
it shows error saying , or ) expected.
How to ensure both the syntax errors are highlighted?
This mostly depends on your context. In other words, how is your JavaScript embedded on the page. If you use close tags ?> and then carry on with some JavaScript it should be able to recognise that this part isn't PHP any more.
You cannot do much about this unfortunately.
ATM injection fragments (different language inside another language) seems to be treated completely differently hence most of the inspections for injected language are disabled or not run at all (I guess it is because each such fragment is treated as separate document which often produced quite a few false positives .. and what is done here is one form of reducing such false alarms -- just my guess).
https://youtrack.jetbrains.com/issue/WI-18963 -- watch this ticket (star/vote/comment) to get notified on any progress.

IE10 (in compatibility mode) generates SCRIPT1015: Unterminated string constant error on valid code?

I have a few small JQuery scripts in SharePoint that currently use hard-coded paths to include jquery itself and CSS, so they are a pain to move around.
I thought i'd use JS and document.write() to include the files using dynamically generated paths including the site root URL.
Problem: I have a piece of what I think is valid JS code, but IE10 spits it out with an "unterminated string" error. if I change the final '</script>' string to anything else it works ok (but of course doesn't result in valid html).
The code itself passes JSlint with a few comments about spacing. Javascriptlint.com generates a warning about "script tag must be empty if a path is specified", but I can fix that by setting the variable "imp" in two lines, firstly generating the linktag, then concatenating the script tag.
Code:
<script language="javascript">
var siteURL= L_Menu_BaseUrl;
var imp= '<link href="' + siteURL + '/SiteAssets/Path/my.css" rel="stylesheet" type="text/css"/>\n'
+ '<script language="javascript" src="' + siteURL + '/lib/js/jquery-1.9.1_min.js">' + '</script>\n';
</script>
I have been staring at this too long, it's probably something really simple. I'm just building an HTML string here but IE seems to be interpreting the final </script> tag, ignoring the fact that it's a literal string in quotes.
Any ideas?
IE seems to be interpreting the final </script> tag, ignoring the fact that it's a literal string in quotes
This is exactly what's happening. One solution is to use '</scr'+'ipt>'. Just break up the closing tag, so it's not interpreted as a close tag.
var imp= '<link href="' + siteURL + '/SiteAssets/Path/my.css" rel="stylesheet" type="text/css"/>\n'
+ '<script language="javascript" src="' + siteURL + '/lib/js/jquery-1.9.1_min.js">' + '</scr' + 'ipt>\n';
EDIT: You can also just do this
... + '<\/script>\n';
Thanks for the helpful comments. Having done more reading on this issue I came to the understanding that using document.write() is generally considered bad practice, or at least something to be avoided.
You can create the <link> and <script> tags entirely in JS code, but that ends up being pretty verbose. I also found it added a layout glitch to my page as the various bits of code wrote the tags that loaded JQuery and the CSS and THEN the browser could finally lay out the page correctly.
I ended up with a hybrid approach, using HTML tags to load the default (production site) location of the dependency files, but then having the script tweak the file paths for the dev site (where a slight layout delay is tolerable).
The result looks like-
<link id="MyCSS" rel="stylesheet" type="text/css" href="/sites/live/SiteAssets/Path/my.css"/>
<script id="JQ" language="javascript" src="/sites/live/lib/js/jquery-1.9.1_min.js"></script>
<script language="javascript">
/*
* Paths for dev / debug
*/
var siteURL= L_Menu_BaseUrl;
if( siteURL != "/sites/live" ) {
document.getElementById("MyCSS").href=
siteURL + "/SiteAssets/Path/my.css";
document.getElementById("JQ").src=
siteURL + "/lib/js/jquery-1.9.1_min.js";
}
</script>

Syntax error while trying to add CDATA within script tags dynamically

So there is an ad code which I try to add to the DOM dynamically, something that looks like this:
<script type="text/javascript"><!--<![CDATA[
JAVASCRIPT CODE
//]]>--></script>
If I paste this code directly in the source code, it works, but if I try to insert it to the DOM with jQuery it throws some untraceable errors - at least I cant trace it. Actually this:
The interesting part is that Firebug connects this error to random scripts in the page which contain jQuery. The ad code is inserted into the DOM this way /element is a jQuery object/:
element.html(data.content);
What I have tried yet:
I have tried to remove the <!-- --> html comment tags.
I have tried to wrap the wole code to a script tag dynamically created by jQuery.
I even tried to remove the CDATA tags, but that broke everything, I think it is important for the main ad handler script provided by the ad manager company.
Any help would be appreciated, thanks in advance!
(Please dont care about the method, it must be done with ajax.)
EDIT: The problem still persists, but I think there must be a problem with the ad code, so I accepted the first useful answer for this topic.
Try like this:
<script type="text/javascript">
/* <![CDATA[ */
...
/* ]]> */
</script>
<script type="text/javascript">
//<![CDATA[
...
//]]>
</script>
<!-- (For styles, it is different) -->
<style type="text/css">
/*<![CDATA[*/
...
/*]]>*/
</style>
And if you really need compatibility with very old browsers that do not recognize the script or style tags resulting in their contents displayed on the page, you can use this:
<script type="text/javascript"><!--//--><![CDATA[//><!--
...
//--><!]]></script>
<!-- (For styles, it is different) -->
<style type="text/css"><!--/*--><![CDATA[/*><!--*/
...
/*]]>*/--></style>
With <![CDATA[ you can embed JS in XML (and XHTML) documents without the need to replace special XML characters like <, >, &, etc by XML entities <, >, & etc
Use this one
<script type="text/javascript">
//<![CDATA[
//YOUR CODE
//]]>
</script>
Let me know if problem still persist.

What exactly do I have to escape inside a `script` element?

What parts of JavaScript code do I have to escape inside a script element in a HTML page? Is <>& enough or too much?
[EDIT] This is related to this bug: http://code.google.com/p/rendersnake/issues/detail?id=15#c6 comment #6
In HTML (and XHTML if you're an evil person that sends your XHTML pages as text/html), script tags are #CDATA, and therefore, the only thing that you shouldn't have in the content is </script>, as that is all that the parser looks for to signal the end of the tag. Don't escape anything; just make sure you don't have </script> in the tag content. For example, if you have a string with a closing script tag, split it up:
var a = '</scr' + 'ipt>';
In XHTML, sent as application/xhtml+xml, script tags are #PCDATA, and therefore, escaping < and & is necessary, unless you can use a <![CDATA[ ... ]]> block to change to #CDATA parsing mode, but in that case, remember that you can't have ]]> in your tag content.
Generally, the only thing I escape is the / in closing tags. Thus:
var msg = "<p>Do you <em>really<\/em> think so, Miss Worthington?<\/p>";
For the rest, I rely on commenting out the entire thing:
<script>
<!--
var msg = "<p>Do you <em>really<\/em> think so, Miss Worthington?<\/p>";
-->
</script>
The comment takes care of the HTML opening tags.
Escaped <, > and & does not work with many browsers. It is good an enough if you put everything inside a CDATA section. Please note that the CDATA section itself will have to be in a JavaScript comment, for this to work with all browsers.
<script>
// <![CDATA[
script here
// ]]>
</script>

Categories

Resources