PDA

View Full Version : Best Practices Javascript



kuau
11-25-2011, 08:30 AM
I have a few questions about Javascript in general...

1. Is there any advantage to embedding the js code in the <head> section of the page as opposed to referencing an external js file? Is one method better in some way, or does it amount to the same thing?

2. If you have the js in the head section and it contains filenames and descriptions, does this get read by the search engines? If not, can you put the js in the body section and have it crawled, or does js never get scanned by search engines?

3. IF js gets read by search engines, do external js files (ie. src=/js/script.js) get indexed or should you always put the script in the main html file?

Thanks!

djr33
11-25-2011, 09:09 AM
I'm not an expert on any of this, but here are some basic answers:

1. Short answer: Technically there is no difference.
Practically, using external files allows you to share one script between pages, so it saves bandwidth (with caching) and makes maintaining a site easier. There's no real advantage to putting things inline except that it's very slightly easier (not having to make extra files).
And it also can be useful if you're using PHP (or another serverside language) to generate dynamic Javascript, such as using PHP to output the values from a database as the values of a JS variable-- you can actually create a dynamic .js file (be sure to send the right headers), but that's complicated, and just putting it inline makes things easier. Alternatively you could put just a minimal few lines (eg, the specifically dynamic code) inline and include the rest in an external file.
Additionally, the only technical difference that I know of is that filenames (URLs) are read differently. In an HTML page (within <script> tags) the locations are relative to the page. But when excluded as an external JS file, the locations are relative to the JS-- note that this is the opposite of CSS files where they still default to the location of the page. Also, this is irrelevant if you're using absolute URLS. Either way, this doesn't really affect anything except that you can't just cut and paste (as you can for everything else in inline/external JS)-- change the relative URLs, and that should fix it.
Finally, it's possible that some browsers might treat commands in both differently for security or something like that. I don't know of any cases like that and I'd ignore the possibility unless I heard differently, but it's something to at least consider if this really matters.

2. What do you mean by "descriptions"? Search engines are designed to understand HTML, not Javascript, so they won't know what's a description and what's not.
Search engines will get the text of inline Javascript, but as far as I know all (major) search engines ignore Javascript at this point, or at the very least it isn't reliable. So it won't matter in that sense.
Secondly, and this is just speculation, but I think it won't matter in the end once search engines do use JS-- search engines look at HTML, so they'll look at what HTML the Javascript generates (eg, an image gallery with filenames and descriptions) and it won't matter where that came from. Search engines at the moment tend to work from text (reading source code), but it's completely possible that they'll soon transition to rendering the page, then looking at the active source code, and going from there. If you want to know what that's like, use Firefox, select all of a page (or part of it) when there's something different due to JS (eg, a rollover change, or a generate image gallery). Right click, and select "view selected source". That will give you an "active" source code view including anything dynamic. It wouldn't be hard to search engines to do something similar.

3. Since at the moment Javascript isn't used (much?) by search engines, I don't think it will matter. And as I said, once they start reading JS, I don't see why they won't use external media was well, since it will be based on the generated page, not the source code (probably). Secondly, there's also a chance that extra-heavy (filesize) pages will be punished, so keeping them light and moving things to external JS files could help. I don't know how likely any of that is, but generally for SEO purposes I wouldn't recommend coding in a bad way (eg, putting all scripts into your HTML source) just because it might be better for SEO (or, for me, even if it is guaranteed to be better).


Now, there is a chance I'm a bit behind and search engines are using JS some, and maybe someone else can comment on that. But if so it's not everywhere and probably limited to certain kinds of code.

kuau
11-25-2011, 02:58 PM
Dear Daniel: Hope you had a good Thanksgiving! And once again I give thanks to you for your very informative answers. I tried what you suggested with FireFox and discovered that it did display the descriptions of the images in the slideshow but for only 2 of them. It did not display the dropdown menu lists. Are you saying that search engines do not currently do this with JS, ie. generate the page and index the generated code? Either way, the bottom line seems to be that JS slideshows and dropdown menus have almost no SEO value. I sure hope that changes as I use both very often and I'm very SEO conscious.

I actually prefer to use external js files so I am happy that you consider that better. Creating dynamic JS files, if it involves changing the JS itself, is a bit beyond me.. hopefully someday.

Anyway, I have wondered about this for a long time so I am grateful to finally know the answer. Mahalo plenty, e :)

jscheuer1
11-25-2011, 05:07 PM
The information in this post is wrong. Please see my next posts in this thread for more information.

Actually, if you have something in the head of a page like:


<script type="text/javascript">

var mygallery=new fadeSlideShow({
wrapperid: "fadeshow1", //ID of blank DIV on page to house Slideshow
dimensions: [250, 180], //width/height of gallery in pixels. Should reflect dimensions of largest image
imagearray: [
["http://i26.tinypic.com/11l7ls0.jpg", "", "", "Nothing beats relaxing next to the pool when the weather is hot."],
["http://i29.tinypic.com/xp3hns.jpg", "http://en.wikipedia.org/wiki/Cave", "_new", "Some day I'd like to explore these caves!"],
["http://i30.tinypic.com/531q3n.jpg"],
["http://i31.tinypic.com/119w28m.jpg", "", "", "What a beautiful scene with everything changing colors."] //<--no trailing comma after very last image element!
],
displaymode: {type:'auto', pause:2500, cycles:0, wraparound:false},
persist: false, //remember last viewed slide and recall within same session?
fadeduration: 500, //transition duration (milliseconds)
descreveal: "ondemand",
togglerid: ""
})


var mygallery2=new fadeSlideShow({
wrapperid: "fadeshow2", //ID of blank DIV on page to house Slideshow
dimensions: [250, 180], //width/height of gallery in pixels. Should reflect dimensions of largest image
imagearray: [
["http://i26.tinypic.com/11l7ls0.jpg", "", "", "Nothing beats relaxing next to the pool when the weather is hot."],
["http://i29.tinypic.com/xp3hns.jpg", "http://en.wikipedia.org/wiki/Cave", "_new", "Some day I'd like to explore these caves!"],
["http://i30.tinypic.com/531q3n.jpg"],
["http://i31.tinypic.com/119w28m.jpg", "", "", "What a beautiful scene with everything changing colors."] //<--no trailing comma after very last image element!
],
displaymode: {type:'manual', pause:2500, cycles:0, wraparound:false},
persist: false, //remember last viewed slide and recall within same session?
fadeduration: 500, //transition duration (milliseconds)
descreveal: "always",
togglerid: "fadeshow2toggler"
})

</script>

Those descriptions get indexed by Google. I was surprised, but a fellow had a Simple Controls Gallery and was worried about SEO. I googled his descriptions and his page came out on top every time. They were exact matches, the only ones, so of course they would.

The information in this post is wrong. Please see my next posts in this thread for more information.

kuau
11-25-2011, 05:49 PM
Dear John: Thanks for showing me a new way to test it. I used your method and determined that when the slideshow descriptions are in an external file, the descriptions are NOT indexed. My question actually relates to your Swiss Army Slideshow. I cannot put the descriptions in the head because the JS filename is a variable and there are about 85 different slideshows that use the page template. But now that you have proven that descriptions in the <head> section ARE indexed, I'm wondering if I can put the JS inside a php file and include it in the <head>. Is that the best way?

Thanks, e :)

jscheuer1
11-25-2011, 06:02 PM
Actually I double checked just now. The page did come up on top for some descriptions, but only because the words in the descriptions were also in the body of the page. For others the ranking wasn't as favorable, even though the words were in the body in places - other sites outranked it. If I put quotes around the descriptions in Google - means search for the exact phrase, nothing came up. So I was just wrong, sorry. If you want SEO on your descriptions, include key words from them in the text in the body.

djr33
11-25-2011, 08:36 PM
That's one thing I forgot to mention: just like creating fallbacks for users without JS, if you want search engines to read everything on your site, then you need to duplicate the content without Javascript. In general, the way to do that is to create non-JS content (eg, text links, rather than a menu) and replace that using Javascript to create the full JS content. Then everyone will see the same information, but for some it will be fancy.

Basically, just imagine that search engines use boring non-JS, non-CSS text-only browsers. (Of course they can see that images exist, but they don't actually see the images. They just relate filenames to descriptions = nearby content.)

jscheuer1
11-26-2011, 05:03 AM
Interesting you should mention that, Daniel. As it so happens, a little while back I wrote a routine for the Ultimate Fade In Slideshow that allows for placing the images, and if any their links and descriptions in the markup. That lets search engines index the images, their descriptions and links. I suppose something like that could be worked out for Swiss Army. If not, U-Fade can probably be made to look like Swiss Army. Or a method can be easily worked out to allow for non-javascript content in the Swiss Army division(s) that will be removed when javascript is available.

jscheuer1
11-27-2011, 04:56 AM
OK, well I was a little bored this morning so I came up with code for Swiss Army that allows for the content to appear in the page's markup. So say you have:


<script type="text/javascript">

//If using image buttons as controls, Set image buttons' image preload here true
//(use false for no preloading and for when using no image buttons as controls):
var preload_ctrl_images=false;

var slides=[]; //FIRST SLIDESHOW
//configure the below images and descriptions to your own.
slides[0] = ["photo5.jpg", "John, Mary and Jesus"];
slides[1] = ["photo1.jpg", "Kissing Fools", "http://www.dynamicdrive.com"];
slides[2] = ["photo2.jpg", "Seated Woman"];
slides[3] = ["photo3.jpg", "The Dog Lovers"];
slides[4] = ["photo4.jpg", "Standing Woman"];
slides[5] = ["photo9_thumb.jpg", "Mona"];

//optional properties for these images:
slides.no_added_linebreaks=1; //use for no added line breaks in formatting of texts and controls
slides.move_desc_up=1;
slides.desc_pic_width=1;

</script>

to define your images. To use markup, change that to:


<script type="text/javascript">

//If using image buttons as controls, Set image buttons' image preload here true
//(use false for no preloading and for when using no image buttons as controls):
var preload_ctrl_images=false;

var slides=[]; //FIRST SLIDESHOW
//configure the below images and descriptions to your own, or use inter_slide.from_markup function.


//optional properties for these images:
slides.no_added_linebreaks=1; //use for no added line breaks in formatting of texts and controls
slides.use_title=1; //use for descriptions as images title attributes
slides.pause=1; //use for pause onmouseover
slides.move_desc_up=1;
slides.desc_pic_width=1;

</script>

And at the end of the main script file (swissarmy.js or swiss_2.js, depending upon which version you're using) add:


inter_slide.from_markup = function(divid, array){
var div = document.getElementById(divid), ims = div.getElementsByTagName('img'), args = arguments, i, p, desc;
div.style.display = 'none';
for (i = ims.length - 1; i > -1; --i){
array[i] = [];
array[i][0] = ims[i].src;
array[i][1] = '';
if((p = ims[i].parentNode) !== div){
if(p.href){array[i][2] = p.href;}
if(p.target){array[i][3] = p.target;}
p.removeChild(ims[i]);
desc = (p = p.innerHTML).replace(inter_slide.from_markup.re, '');
if(desc){array[i][1] = p;}
}
}
new inter_slide(args[1], args[2], args[3], args[4]);
};
inter_slide.from_markup.re = /\s/g;

And in the body of the page, instead of something like:


<div id="show0">
<script type="text/javascript">
//Notes on Parameters: The only required parameter is the slides_array_name. If Width is used, so must Height.
//Interval is optional too. It is always last, either fourth after Width and Height or second after Slides_array_name.
//Usage: new inter_slide(Slides_array_name, Width, Height, Interval)
new inter_slide(slides, 140, 225)
</script>
</div>

do like:


<div id="myslides">
<div><img src="photo5.jpg" alt="slideshow image" title="">John, Mary and Jesus</div>
<a href="http://www.dynamicdrive.com" target="_new"><img src="photo1.jpg" alt="slideshow image" title="">Kissing Fools</a>
<div><img src="photo2.jpg" alt="slideshow image" title="">Seated Woman</div>
<div><img src="photo3.jpg" alt="slideshow image" title="">The Dog Lovers</div>
<div><img src="photo4.jpg" alt="slideshow image" title="">Standing Woman</div>
<div><img src="photo9_thumb.jpg" alt="slideshow image" title="">Mona</div>
</div>
<div id="show0">
<script type="text/javascript">
//Notes on Parameters: The only required parameters are the Div_id and Slides_array_name. If Width is used, so must Height.
//Interval is optional too. If used it's always last, either fifth after Width and Height or third after Div_id and Slides_array_name.
//Usage: inter_slide.from_markup(Div_id, Slides_array_name, Width, Height, Interval)
inter_slide.from_markup('myslides', slides, 140, 225)
</script>
</div>

kuau
11-27-2011, 02:54 PM
Dear John: WOW! I must say you are productive when you are bored. Thank you so much for doing that.

If I understand correctly, I am to totally replace the JS section that defines the images and looks like this...


var slides=[]; //FIRST SLIDESHOW
//configure the below images and descriptions to your own.
slides[0] = ["photo5.jpg", "John, Mary and Jesus"];
slides[1] = ["photo1.jpg", "Kissing Fools", "http://www.dynamicdrive.com"];
slides[2] = ["photo2.jpg", "Seated Woman"];
slides[3] = ["photo3.jpg", "The Dog Lovers"];
slides[4] = ["photo4.jpg", "Standing Woman"];
slides[5] = ["photo9_thumb.jpg", "Mona"];


with html like this...


<div id="slides">
<div><img src="photo5.jpg" alt="slideshow image" title="">John, Mary and Jesus</div>
<a href="http://www.dynamicdrive.com" target="_new"><img src="photo1.jpg" alt="slideshow image" title="">Kissing Fools</a>
<div><img src="photo2.jpg" alt="slideshow image" title="">Seated Woman</div>
<div><img src="photo3.jpg" alt="slideshow image" title="">The Dog Lovers</div>
<div><img src="photo4.jpg" alt="slideshow image" title="">Standing Woman</div>
<div><img src="photo9_thumb.jpg" alt="slideshow image" title="">Mona</div>
</div>


If that is the case, I'll use an include for that section. My question then is, can I put this section of JS below in the php include?...


<script type="text/javascript">

//If using image buttons as controls, Set image buttons' image preload here true
//(use false for no preloading and for when using no image buttons as controls):
var preload_ctrl_images=false;

var slides=[]; //FIRST SLIDESHOW
//configure the below images and descriptions to your own, or use inter_slide.from_markup function.


//optional properties for these images:
slides.no_added_linebreaks=1; //use for no added line breaks in formatting of texts and controls
slides.use_title=1; //use for descriptions as images title attributes
slides.pause=1; //use for pause onmouseover
slides.move_desc_up=1;
slides.desc_pic_width=1;
</script>

I also have a similar unrelated question that I'm not sure deserves a new thread. Is it OK to put a fews lines of JS into the body of a page that I would normally have put in the <head> section? It's for a pop-up window. Does it matter where the JS goes?

Thanks very much. You're welcome to be bored at my house any time. :)

jscheuer1
11-27-2011, 05:09 PM
Now, of course in all of this on the page you need to, if they are different, use your own variable names and of course your own images and descriptions and links if any. The code added to the main script is generic, it need not be edited, shouldn't be unless there's some real problem with it.

OK, you still need the:


var slides=[];

part in the script block in the head, along with any properties you have defined for that slideshow. But you have that right in your third code block in your post.

The inter_slide.from_markup() function doesn't create the array, it only populates it.

And yes, anything can be in an include. However, once you do that, if there are any problems, it gets complicated. Best to start out with it on the page, make sure that's working. And if you want to make it external, since it's a script you can make it be an external script rather than a PHP include. That is often less prone to errors as long as you know how to make an on page script into an external script.

If you have any problems along the way that you cannot solve, give me a link to a demo.



As to your other question, it depends. Generally it's OK. In some cases though it's best to do that as the first thing after the opening <body> tag. In others it's best to do it as the last thing before the closing </body> tag. If it's a true pop up window, not a pop up division that looks like a window, it will likely be OK almost anywhere.

Again, if you have problems with it, give me a link to a demo.