PDA

View Full Version : Multiple Use of Scripts once on page



Imran
09-26-2006, 08:57 AM
Please advice why conflict takes place when we run multiple scripts on the same page only one runs while the others is not visible what im doing wrong and what is the remedy
Thanks

codeexploiter
09-26-2006, 09:35 AM
If you can provide the code it would be great for others to comment on.

ItsMeOnly
09-26-2006, 09:38 AM
Remember that scripts are "threaded" and hierarchical, that means when you're calling a function, it has to be already defined. It's not true that scripts are run one by one, I suspect you might work on variables that you have been defining as global (affecting entire page), and conflicts arise when scripts access them at the same time.

jscheuer1
09-26-2006, 09:56 AM
The most common reason is a conflict in the two scripts' onload handlers. If all scripts were written with this sort of onload handler, there would be much less of these conflicts:


if ( typeof window.addEventListener != "undefined" )
window.addEventListener( "load", myInitFunction, false );
else if ( typeof window.attachEvent != "undefined" )
window.attachEvent( "onload", myInitFunction );
else {
if ( window.onload != null ) {
var oldOnload = window.onload;
window.onload = function ( e ) {
oldOnload( e );
myInitFunction();
};
}
else
window.onload = myInitFunction;
}

But, your average script's onload handler is like one of the following:

In the body tag -

<body onload="myInitFunction();">

Or in script -

onload=myInitFunction;
or -

window.onload=myInitFunction;
or -

document.onload=myInitFunction;

There are other ways. With any two given scripts, the two onload events can usually be combined:

In the body tag:

<body onload="myInitFunction();myOtherInitFunction();">

Or in script -

onload=function(){
myInitFunction();
myOtherInitFunction();
}

There can be other conflicts but, the above is usually all it is. Many scripts have no onload handler. If there is a conflict with one of these, it has to be something else. Global variable, function and id names shared between scripts can cause problems. In these cases, the duplicate names must be made unique to each individual script. In the case of variable and function names, sometimes a global can be made local. Otherwise, it must be made unique to a given script.

mwinter
09-26-2006, 11:40 AM
Remember that scripts are "threaded" and hierarchical, that means when you're calling a function, it has to be already defined. It's not true that scripts are run one by one ...

Depending on what you mean, all of that is either wrong or at least misleading (as I read it).

There is no concurrent execution within scripts. Though host objects might perform asynchronous actions (the XMLHttpRequest object is one example), script code is never interrupted and executes to completion. Consider:



var flag = false,
c = 0;

setTimeout(function() {
alert(c + ' ' + flag);
}, 100);
while (++c < 1000000);
flag = true;

On my machine, it takes approximately 2.5 seconds for the alert to appear, well beyond the time-out value. Both c and flag have been set to the values that one would expect had the script completed (1000000 and true, respectively).

As for, "when you're calling a function, it has to be already defined":



myFunction();

function myFunction() {
alert('Hello world!');
}

Any browser that errors out with "myFunction is not defined" is broken.

Mike

ItsMeOnly
09-26-2006, 07:38 PM
Depending on what you mean, all of that is either wrong or at least misleading (as I read it).
OK, so I'll show you what I meant by "threading" and concurrent execution.


<div id="mytest"></div>
<script type="text/javascript">
hello = "Hello, world";

mytestObj = document.getElementById('mytest');

function displayLetter(x) {
mytestObj.innerHTML += hello.charAt(x);
}

for (x=0; x < 100; x++) {
setTimeout('displayLetter('+x+')', (Math.random() * 100));
}
</script>

The result of this code will be "Hello, world" displayed nearly never, since setTimeout "forks" the execution.

As for hierarchical:
In my understanding, for example:

<body onmousemove="myfunction()">
will have precedence over

<div onmousemove="myfunction()">
since div will most likely the child.
Or am I wrong?

Anyway, I experienced "myFunction is not defined" case pretty often, especially when using multiple external scripts- so I guess it's not so incorrect.

mwinter
09-26-2006, 11:41 PM
OK, so I'll show you what I meant by "threading" and concurrent execution.


<div id="mytest"></div>
<script type="text/javascript">
hello = "Hello, world";

mytestObj = document.getElementById('mytest');

function displayLetter(x) {
mytestObj.innerHTML += hello.charAt(x);
}

for (x=0; x < 100; x++) {
setTimeout('displayLetter('+x+')', (Math.random() * 100));
}
</script>


This demonstrates neither concept. The setTimeout delays execution of code, that's all. Two functions, for example, will never run asynchronously, so trying to apply terms that infer precisely that is misleading.



The result of this code will be "Hello, world" displayed nearly never, since setTimeout "forks" the execution.

The result will nearly never be the original string because for that to happen, the initial twelve return values from the Math.random method must be in increasing order. After those first twelve, further execution is pointless: passing the value of x to the charAt method will always return an empty string.



As for hierarchical:
In my understanding, for example:

<body onmousemove="myfunction()">
will have precedence over

<div onmousemove="myfunction()">

Precedence in what regard? Moreover, how does event flow make scripts hierarchical?



since div will most likely the child.

A div element may only ever be a descendant of a body element, so possibly a child, but never an ancestor or parent.



Or am I wrong?

As it's not clear what you mean, I couldn't say. However, "precedence" tends to confer "coming first", or "more important", but between two non-capturing event listeners, the one nearest the document root is neither.



Anyway, I experienced "myFunction is not defined" case pretty often,

Then you're clearly doing something wrong. Between code in different script elements, the code that is depended upon must occur first, but the reason for that should be obvious: the browser won't pass the code to the script interpreter until it has encountered it in the markup. Within a script, declaration order is irrelevant.



... so I guess it's not so incorrect.

If, and only if, you meant the above (and it's not clear that you did).

Mike

jscheuer1
09-27-2006, 04:33 AM
A div element may only ever be a descendant of a body element, so possibly a child, but never an ancestor or parent.


The result of this code will be "Hello, world" displayed nearly never, since setTimeout "forks" the execution.

Topic gentlemen. This wasn't a thread on what javascript is or isn't, nor was it about the finer points of the DOM. If I were the OP, I would be a bit miffed that my thread had been hijacked for these discussions.

Why not start a new thread for this? It certainly is interesting.

Imran
09-27-2006, 04:50 AM
i want to use these code twice on the same page but not working properly
please send me remedy.
<body onload="Carousel()", "Carousel1()">
<script type="text/javascript">

/***********************************************
* Carousel Slideshow script- &#169; Ger Versluis 2003
* Permission granted to DynamicDrive.com to feature script
* This notice must stay intact for legal use
* Visit http://www.dynamicdrive.com/ for full source code
***********************************************/

/********************************************************
Create a div with transparent place holder in your html
<div id="Carousel" style="position:relative">
<img src="car6.gif" width="200" height="100">
</div>
placeholder width:
4 sided: 1.42 * carousel image width + 3
6 sided: 2 * carousel image width +4
8 sided: 2.62 * carousel image width + 5
12 sided: 3.87 * carousel image width + 7
placeholder height:
carousel image height+2

Insert onload in body tag
*********************************************************/

// 7 variables to control behavior
var Car_Image_Width=200;
var Car_Image_Height=100;
var Car_Border=true; // true or false
var Car_Border_Color="black";
var Car_Speed=5;
var Car_Direction=true; // true or false
var Car_NoOfSides=8; // must be 4, 6, 8 or 12

/* array to specify images and optional links.
For 4 sided carousel specify at least 2 images
For 6 sided carousel specify at least 3
For 8 sided carousel specify at least 4
For 12 sided carousel specify at least 6
If Link is not needed keep it ""
*/
Car_Image_Sources=new Array(
"car1.jpg","http://www.dynamicdrive.com",
"car2.jpg","http://www.javascriptkit.com",
"car3.jpg","", //this slide isn't linked
"car4.jpg","", //this slide isn't linked
"car5.jpg","", //this slide isn't linked
"car6.jpg","http://www.codingforums.com" // NOTE No comma after last line
);

/***************** DO NOT EDIT BELOW **********************************/
CW_I=new Array(Car_NoOfSides/2+1);C_ClcW=new Array(Car_NoOfSides/2);
C_Coef=new Array(
3*Math.PI/2,0,3*Math.PI/2,11*Math.PI/6,Math.PI/6,3*Math.PI/2,7*Math.PI/4, 0,
Math.PI/4,3*Math.PI/2,5*Math.PI/3,11*Math.PI/6,0,Math.PI/6,Math.PI/3);
var C_CoefOf=Car_NoOfSides==4?0:Car_NoOfSides==6?2:Car_NoOfSides==8?5:9;
C_Pre_Img=new Array(Car_Image_Sources.length);
var C_Angle=Car_Direction?Math.PI/(Car_NoOfSides/2):0,C_CrImg=Car_NoOfSides,C_MaxW,C_TotalW,
C_Stppd=false,i,C_LeftOffset,C_HalfNo=Car_NoOfSides/2;

function Carousel(){
if(document.getElementById){
for(i=0;i<Car_Image_Sources.length;i+=2){
C_Pre_Img[i]=new Image();C_Pre_Img[i].src=Car_Image_Sources[i]}
C_MaxW=Car_Image_Width/Math.sin(Math.PI/Car_NoOfSides)+C_HalfNo+1;
Car_Div=document.getElementById("Carousel");
for(i=0;i<C_HalfNo;i++){
CW_I[i]=document.createElement("img");Car_Div.appendChild(CW_I[i]);
CW_I[i].style.position="absolute";
CW_I[i].style.top=0+"px";
CW_I[i].style.height=Car_Image_Height+"px";
if(Car_Border){
CW_I[i].style.borderStyle="solid";
CW_I[i].style.borderWidth=1+"px";
CW_I[i].style.borderColor=Car_Border_Color}
CW_I[i].src=Car_Image_Sources[2*i];
CW_I[i].lnk=Car_Image_Sources[2*i+1];
CW_I[i].onclick=C_LdLnk;
CW_I[i].onmouseover=C_Stp;
CW_I[i].onmouseout=C_Rstrt}
CarImages()}}

function CarImages(){
if(!C_Stppd){
C_TotalW=0;
for(i=0;i<C_HalfNo;i++){
C_ClcW[i]=Math.round(Math.cos(Math.abs(C_Coef[C_CoefOf+i]+C_Angle))*Car_Image_Width);
C_TotalW+=C_ClcW[i]}
C_LeftOffset=(C_MaxW-C_TotalW)/2;
for(i=0;i<C_HalfNo;i++){
CW_I[i].style.left=C_LeftOffset+"px";
CW_I[i].style.width=C_ClcW[i]+"px";
C_LeftOffset+=C_ClcW[i]}
C_Angle+=Car_Speed/720*Math.PI*(Car_Direction?-1:1);
if((Car_Direction&&C_Angle<=0)||(!Car_Direction&&C_Angle>=Math.PI/C_HalfNo)){
if(C_CrImg==Car_Image_Sources.length)C_CrImg=0;
if(Car_Direction){
CW_I[C_HalfNo]=CW_I[0];
for(i=0;i<C_HalfNo;i++)CW_I[i]=CW_I[i+1];
CW_I[C_HalfNo-1].src=Car_Image_Sources[C_CrImg];
CW_I[C_HalfNo-1].lnk=Car_Image_Sources[C_CrImg+1]}
else{ for(i=C_HalfNo;i>0;i--)CW_I[i]=CW_I[i-1];
CW_I[0]=CW_I[C_HalfNo];
CW_I[0].src=Car_Image_Sources[C_CrImg];
CW_I[0].lnk=Car_Image_Sources[C_CrImg+1]}
C_Angle=Car_Direction?Math.PI/C_HalfNo:0;C_CrImg+=2}}
setTimeout("CarImages()",50)}

function C_LdLnk(){if(this.lnk)window.location.href=this.lnk}
function C_Stp(){this.style.cursor=this.lnk?"pointer":"default";C_Stppd=true;}
function C_Rstrt(){C_Stppd=false}
</script>

jscheuer1
09-27-2006, 05:08 AM
i want to use these code twice on the same page but not working properly
please send me remedy.
<body onload="Carousel()", "Carousel1()">
<script type="text/javascript">


Global variable, function and id names shared between scripts can cause problems. In these cases, the duplicate names must be made unique to each individual script. In the case of variable and function names, sometimes a global can be made local. Otherwise, it must be made unique to a given script.

That's always going to be the problem when trying to run two of the same script on one page unless the script is object oriented.

However, you are lucky. Harry Armadillo has already written an object oriented version of this very script and it is available here on Dynamic Drive:

http://www.dynamicdrive.com/dynamicindex14/carousel2.htm


From the Demo Page:

Description: This carousel image slideshow, with its object oriented design, redefines robustness. The script supports vertical and horizontal scrolling, optional linking, title attributes, configurable visible sides, and more. Furthermore, multiple, different versions of this script can be invoked on the same page. Wow!