tags:

views:

452

answers:

3

What is the best way to reference or include a file using Javascript, looking for the closest functionality of PHP's include() ability.

+5  A: 

I would check out Javascript equivalent for PHP's include:

This article is part of the 'Porting PHP to Javascript' Project, which aims to decrease the gap between developing for PHP & Javascript.

There is no direct equivalent - you can either go with the function I linked above or use document.write to write out a new script tag with a src pointing to the file you wish to include.

Edit: Here is a rudimentary example of what I mean:

function include(path) {
    document.write(
     "<script type=\"text/javascript\" src=\"" + path + "\"></script>"
    );
}

Edit 2: Ugh, what an ugly example - here is a better one:

function include(path) {
    script = document.createElement("script");
    script.setAttribute("type", "text/javascript");
    script.setAttribute("src", path);

    if (head = document.getElementsByTagName("head")[0]) {
     head.appendChild(script);
    }
}

document.write is a hackish way of doing things and I shouldn't have recommended it. If you go with one of my examples please use the second one.

Andrew Hare
That seems like the right direction but I'm looking for something really small that can be embedded directly into an HTML page. Sadly, some of the work I'm doing right now is looking for something ala Google AdWords, where a bunch of sites will have the same code, and then our server will run an application that will generate code.
dmanexe
if it's not cross-domain loading then evaling an xmlhttprequest responseText will also work. That is how the recently revived JSAN project did it initially.
Jeremy Wall
A: 

I have a script that I wrote a while back (using Mootools) that allows for one to include javascript files on the fly (with a callback function after its loaded). You can modify it to work the library of your choice if you choose.

Note the gvi prefix is just my namespace and that gvi.scripts is an array containing all the javascript files currently included on the page, those can be removed if you want. Also, the filename function can be removed, that was just added to make my life easier [require('some-script') vs require('js/some-script.js')].

//if dom isn't loaded, add the function to the domready queue, otherwise call it immediately
gvi.smartcall = function(fn) {
    return (Browser.loaded) ?  fn() : window.addEvent('domready', fn);
}

//For dynamic javascript loading
gvi.require = function(files, callback, fullpath) {
    callback = callback || $empty;
    fullpath = fullpath || false;
    var filename = function(file) {
     if (fullpath == true) return file;
     file = ( file.match( /^js\/./ ) ) ? file : "js/"+file;
     return ( file.match( /\.js$/ ) ? file : file+".js" );
    }

    var exists = function(src) {
     return gvi.scripts.contains(src);
    }

    if ($type(files) == "string") {
     var src = filename(files);

     if (exists(src)) {
      gvi.smartcall(callback);
     } else {
                        new Asset.javascript( src, {
       'onload' : function() {
        gvi.scripts.push(src);
        gvi.smartcall(callback);
       }
      });
     }

    } else {
     var total = files.length, loaded = 0;
     files.each(function(file) {
                        var src = filename(file);

      if (exists(src) && loaded == total) {
       gvi.smartcall(callback);

      } else if (exists(src)) {
       loaded++;
      } else {
                            new Asset.javascript( src, {
        'onload' : function() {
         gvi.scripts.push(src);
         loaded++;
         if (loaded == total) gvi.smartcall(callback);
        }
       });
      }
     });
    }
}

And you call it like

gvi.require('my-file', function() {
  doStuff();
});

//or
gvi.require(['file1', 'file2'], function() {
  doStuff();
});
tj111
A: 

jQuery has a plugin for this: http://plugins.jquery.com/project/include

Ken Keenan