Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

Check if file exists in JavaScript

Posted on 2007-07-30
4
Medium Priority
?
462 Views
Last Modified: 2008-01-09
Hello,

I am importing a number of .js files in my JavaScript app, and I want to be able to check if the file exists before I import the file.

The way I am importing them is something like this:

script.src = 'configuration/wordlist-' + number + '.js';
script.type = 'text/javascript';
script.defer = true;
var head = document.getElementsByTagName('head').item(0);
head.appendChild(script);

with number been a variable that I have set before this script runs.

I want to be able to check if that file exists before I import it, or, if it can't import (/doesn't exists), runs a function of my choice. Either way would work.

If this is possible a solution would be greatly appreciated.

Thanks!
0
Comment
Question by:dh-s
  • 3
4 Comments
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 19592343
You could try to read it with an xmlhttp connection...
that means the file MUST come from the same server as the page you test it in
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 19592353
Using for example the "HEAD" request
http://www.jibbering.com/2002/4/httprequest.html
0
 
LVL 14

Assisted Solution

by:bugs021997
bugs021997 earned 400 total points
ID: 19592370
function FileExists(strURL)
{
    oHttp = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();    
    oHttp.open("GET", strURL, false);
    oHttp.send();
    return oHttp.responseText.indexOf("404 - File not found") > 0 ? false : true;
}


OR

function checkIfRemoteFileExists(fileToCheck)
{
var tmp=new Image;
tmp.src=fileToCheck;
if(tmp.complete)
{ window.alert(fileToCheck+" is available"); }
else
{ // Not got it yet - retry for a few seconds...
window.setTimeout('checkIfRemoteFileExists(fileToC heck)', 1000);
}
}

checkIfRemoteFileExists('http://www.where-ever.com/abc.html');
0
 
LVL 75

Accepted Solution

by:
Michel Plungjan earned 600 total points
ID: 19592720
Or without loading the file (from the link I already gave
http://www.jibbering.com/2002/4/httprequest.html ):

var xmlhttp=false;
/*@cc_on @*/
/*@if (@_jscript_version >= 5)
// JScript gives us Conditional compilation, we can cope with old IE versions.
// and security blocked creation of the objects.
 try {
  xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
 } catch (e) {
  try {
   xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
  } catch (E) {
   xmlhttp = false;
  }
 }
@end @*/
if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
      try {
            xmlhttp = new XMLHttpRequest();
      } catch (e) {
            xmlhttp=false;
      }
}
if (!xmlhttp && window.createRequest) {
      try {
            xmlhttp = window.createRequest();
      } catch (e) {
            xmlhttp=false;
      }
}

 xmlhttp.open("HEAD", script.src ,true);
 xmlhttp.onreadystatechange=function() {
  if (xmlhttp.readyState==4) {
   if (xmlhttp.status==200) {
      script.type = 'text/javascript';
      script.defer = true;
      var head = document.getElementsByTagName('head').item(0);
      head.appendChild(script);
   }
    else if (xmlhttp.status==404) alert("URL doesn't exist!")
     else alert("Status is "+xmlhttp.status)
  }
 }
 xmlhttp.send(null)
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In my daily work (mainly using ASP.net), I need to write a lot of JavaScript code. One of the most repetitive tasks I do are the jQuery Ajax calls. You know: (CODE) I don't know if for you it's the same, but for me is soooo tedious to write the …
Having worked on larger scale sites, we found out that you are bound to look at more scalable solutions to integrating widgets, code snippets or complete applications and mesh them into functional sites, in any given composition. To share some of…
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…
Suggested Courses

571 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