Solved

Test If JavaScript File Exists

Posted on 2009-07-15
11
2,545 Views
Last Modified: 2012-06-21
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

0
Comment
Question by:marcparillo
  • 5
  • 3
  • 2
  • +1
11 Comments
 
LVL 14

Expert Comment

by:flob9
ID: 24865337
Try a short setTimeout to load this, or ajax ...
0
 
LVL 4

Accepted Solution

by:
jamesbcox1980 earned 250 total points
ID: 24865910
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
 
LVL 4

Expert Comment

by:jamesbcox1980
ID: 24865927
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
 
LVL 13

Assisted Solution

by:Murali Murugesan
Murali Murugesan earned 250 total points
ID: 24865931
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
 
LVL 3

Author Comment

by:marcparillo
ID: 24865936
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
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 3

Author Comment

by:marcparillo
ID: 24867756
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
 
LVL 3

Author Comment

by:marcparillo
ID: 24867895
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
 
LVL 13

Expert Comment

by:Murali Murugesan
ID: 24867938
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
 
LVL 3

Author Comment

by:marcparillo
ID: 24868274
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
 
LVL 13

Expert Comment

by:Murali Murugesan
ID: 24875349
>>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
 
LVL 3

Author Comment

by:marcparillo
ID: 24985249
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

Featured Post

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

This article will give core knowledge of JavaScript and will head in to your first JavaScript program. I am Durvesh Naik and I am here to deal with this series of JavaScript. I will teach you JavaScript in part wise , as its quite boring to read big…
jQuery is a JavaScript library that greatly simplifies JavaScript programming. AJAX is an acronym formed from "Asynchronous JavaScript and XML."  AJAX refers to any communication between client and server, when the human client does not observe a…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

759 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now