I’ve seen many posts over the years asking if there is a javascript equivalent to the cc++ #include command, or Java’s import command for including source files. Today I decided to whip one up using Prototype. Check out the demo here.
Here is my HTML page. The code for the include statement is embedded at the top of the page. The code using the statement is in a block at the bottom of the page.
1 3 4 5 6 #include statement for prototype/scriptaculous 7 8 9 31 32 33 34 #include statement for javascript 35 36 37 The Prototype #include statement: 38 39 40 function include (jsFile) { 41 new Ajax.Request(jsFile, { 42 method: 'get', 43 asynchronous : false, 44 onSuccess: function(transport) { 45 // Evaluate the javascript 46 eval(transport.responseText); 47 }, 48 49 onFailure : function() { 50 alert("Failure including file: " + jsFile); 51 } 52 53 }); 54 55 } 56 57 58 The javascript file I'm including: 59 60 61 hello.js 62 63 64 65 sayhello = function () { 66 alert("I'm saying hello!"); 67 } 68 69 70 71 Using the include statement: 72 73 74 75 include('hello.js'); 76 77 sayhello(); 78 79 80 89 90 91
The var command takes the function out of the global scope for some reason. Here is a demo with the non-working code.
For windows IE you need to add the evalScript() instead of eval()….
Check it out
http://www.exit12.org/archives/12
It’s so amazing for us! Thanks!