Test If JavaScript File Exists

I am trying to come up with a client-side solution to test if a javascript file is located on a remote server before continuing with a particular block of code.  It has to be a client-side solution.   I ran into a problem recently where a remote server containing the javascript file was off-line temporarily, causing my webpage to hang up during the http request.  I've looked for various solutions on-line.  Here's one that looks promising, but I can't get it to recognize if a file DOESN'T exist.   Ideally, if the file doesn't exist, then the 'fileExists' function would be skipped and the rendering of the webpage would continue, uninterrupted.

Any suggestions are greatly appreciated!
function loadScript(url,callback){
 
    var script = document.createElement("script")
    script.type = "text/javascript";
 
    if (script.readyState){  //IE
        script.onreadystatechange = function(){
            if (script.readyState == "loaded" || script.readyState == "complete"){
                script.onreadystatechange = null;
                callback();
            }
        };
    } else {  //Others
        script.onload = function(){
            callback();
        };
    }
 
    script.src = url;
    document.head.appendChild(script);
}
function fileExists() {
alert('file exists'); /// more code here
}
loadScript("http://www.remotedomain.com/jscript/script_here.js",fileExists);

Open in new window

LVL 3
marcparilloAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

flob9Commented:
Try a short setTimeout to load this, or ajax ...
0
jamesbcox1980Commented:
I have a better solution.  Number 1, you can't use http requests on remote servers in javascript.  So, while you can load the scripts, you can't monitor their status and whatnot like you can with files on the same server.  This is a security issue address by recent browsers.

What you can do instead, is load the JS file into an IMG.
var tmpFile;
function checkJS(url){
    tmpFile = new Image();
    tmpFile.src=url;
    tmpFile.onload=writeJS(url);
}
function errorHandler(){
    //Add something here to tell the script
	//what to do if the script doesn't exist.
	//for testing, uncomment the following line:
	//alert("File not loaded. Halting script.")
}
function writeJS(url){
	if(tmpFile>0){
    //for testing, uncomment the following line:
	    //alert("This file exists, will proceed with writing")
    	tmpFile=null;
    	var newScript=document.createElement('SCRIPT');
    	newScript.type='text/javascript';
    	newScript.src=url;
    	document.body.appendChild(newScript);
	}else{
		errorHandler();
	}
}

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
jamesbcox1980Commented:
Oops, I missed something there, let me check it and get back to you.  I know this is the way, though, I've used it before.
0
Determine the Perfect Price for Your IT Services

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden with our free interactive tool and use it to determine the right price for your IT services. Download your free eBook now!

Murali MurugesanFull stack Java developerCommented:
try this way,

assuming chkDate is a function in script_here.js. You can replace window.chkDate  with any valid function from the script_here.js.


<SCRIPT LANGUAGE="JavaScript" SRC="http://www.remotedomain.com/jscript/script_here.js" defer>
</SCRIPT>
<script>
      function checkFunc(){      
                  if(window.chkDate){  // assuming chkDate is a function in script_here.js
                        alert('File exists');
                  }else{
                   alert('File does not exist');
                  }                                          
      }
</script>
 </HEAD>

 <BODY>
  <INPUT TYPE="button" onclick="checkFunc()" value="Click"/>
 </BODY>

-Murali*
0
marcparilloAuthor Commented:
Thank you.  I was trying something like that but I ran into problems trying to load two javascript files:  one is a straight .js file and the other is a dynamic .php file that creates a line of javascript.   This is what the code looked like before I attempted a workaround like you suggested:

<div id="player">
<script type="text/javascript" src="http://www.domain/jscript/AC_RunActiveContent.js"></script>
<script type="text/javascript" src="http://www.domain/media/index.php?sid=FrEkyqqD&pid=uzDHnyEB1247516732"></script>
</div>

The code above is pretty straight forward.  The loophole is when the files on www.domain.com are off-line.  So, following your suggestion, I need to come up with a way to load the .js and .php files as javascript only if the server they're on is alive -- which can be easily tested with the image loading technique you recommended.

0
marcparilloAuthor Commented:
Thank you MuraliKanth,
I like your solution but there's one hitch:  the remote .js file I'm trying to access uses document.write, so if I defer it, won't it replace the entire page with its document.write command as soon as the browser gets to it?  
0
marcparilloAuthor Commented:
I used elements of both of your ideas to come up with this, but I still can't get the content to load.  I can test the presence of the .gif image on the remote server, load the AC_RunActiveContent.js file, but when after loading the JS function from the php file, nothing shows.   I think it's because I'm trying to attach dynamically-generated JS content into the "flash_insert" DIV.  



<div id="flash_insert"></div>
 
<script type="text/javascript">
checkJS('http://www.remotedomain/test.gif');
function checkJS(url){
    var oImg = new Image();
    oImg.onload = function(){onImageEvent(true);};
    oImg.onerror = function(){onImageEvent(false)};
    oImg.src = url; 
}
function errorHandler(){alert("File not loaded. Halting script.")}
function onImageEvent(loaded)
  {
    if (loaded)
    {
	
			
	var url = 'http://www.remotedomain/AC_RunActiveContent.js';         
		
	alert("This file exists, will proceed with writing")
    	tmpFile=null;
    	newScript=document.createElement('SCRIPT');
    	newScript.type='text/javascript';
    	newScript.src=url;
    	document.body.appendChild(newScript);
         if (window.AC_FL_RunContent) {alert('js file loaded'); showWidget();}
	
		
    }
	else {errorHandler();}
  }
	
 
function showWidget() {
	
         // php file creates dynamically-generated JS function to show FLASH file   
	var url2 = 'http://www.remotedomain/flash_insert_function_generated_by_javascript/index.php';
	newScript=document.createElement('SCRIPT');
    	newScript.type='text/javascript';
    	newScript.src=url2;
    	document.getElementById('flash_insert').appendChild(newScript);	
}
</script>

Open in new window

0
Murali MurugesanFull stack Java developerCommented:
So at present if you have the external .js file does it overwrite the page?. By the way do have document.write inside a function? if so only on calling it, it would write the document.

Defer - i have used to remove the delay in rendering the page. You need to provide more details on your page flow if you have document.write in the .js file.
 

From the above code u posted , i dont think creating a dynamic element would include the external .js file. It would just create a script element with reference to the external js. What you should do , is after checking the file existence you should write the entire contents of .js dynamically . Only then it would execute the functions.

-Murali*
0
marcparilloAuthor Commented:
Thank you MuraliKanth,

In my code above, when I test for window.AC_FL_RunContent, get a response that the function does exist after AC_FL_RunContent.js is loaded into the new SCRIPT element.  I don't understand what you mean by "... write the entire contents of .js dynamically."  

Here's what I would like to happen: (1) AC_FL_RunContent.js added to the HTML page as an external .js file containing all of the functions necessary to add a .swf file to a webpage.  (2)  I check for the existence of the AC_FL_RunContent function as proof that the .js script and all of its functions are now available.  (3) Somehow load the .php file so that the resulting AC_FL_RunContent that the php file creates is added to the HTML page where the "flash_insert" div appears in the HTML page.  I can get to step 2, but after that, something gets lost.

I've attached the JS (txt) file that I'm adding to the page.

Here is also an example of the code that is created from the PHP file to work with the added .js file:

AC_FL_RunContent( 'codebase','http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,19,0','width','300','height','310','src','http://www.remotedomain/path/to/flash/file','quality','high','pluginspage','http://www.macromedia.com/go/getflashplayer','movie','http://www.remotedomain/path/to/flash/file','flashVars','flash=1&test=1,'allowScriptAccess','always','auto_play','true','base','.' );

Open in new window

AC-RunActiveContent.txt
0
Murali MurugesanFull stack Java developerCommented:
>>I don't understand what you mean by "... write the entire contents of .js dynamically."  

     By this i mean. You need to bring in the .js file contents (all the .js functions) dynamically into ur page instead of including a script element which has reference to the .js file.

First thing i should admit is i haven;t worked on PHP and my knowledge on flash is very less.

AC_FL_RunContent  seems to return a document.write which would rewrite your complete page.
i am not sure ""flash_insert" div appears in the HTML page" whether u r trying to write the contents into the div tag of html using document.write?


0
marcparilloAuthor Commented:
So, I figured out a solution.  I add the following Javascript code to the page.  The Javascript first makes sure it can retrieve a 1x1 pixel .gif image from the server.   If it can, then it calls the .php file that generates the Javascript I want to add to the <head> portion of the page.  If the .gif can't be found (server is down), then the script exits silently, allowing the rest of the  HTML to render.

The .php file writes Javascript using innerHTML to add content to the div I want to add, in this case, a small Flash insert:

header("Content-type: text/javascript");
print "document.getElementById('player').innerHTML = \"< lots of code to add Flash object to HTML page >\";";


<div id='player'>
<script type='text/javascript'>
       function cJS(url){
         var img=new Image();
         img.onload=function(){e(true);};
         img.onerror=function(){e(false)};
         img.src=url;
        }
 
        function e(l){
          if(l){
         var node=document.createElement('script');document.getElementsByTagName('head')[0].appendChild(node);
         node.setAttribute('type','text/javascript');
         node.setAttribute('src','http://path/to/php/script.php');
            }
         }
        
        cJS('http://path/to/image/to/ping.gif');
    </script>
</div>

Open in new window

0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.