<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title> &#187; javascript import</title>
	<atom:link href="http://www.anzaan.com/tag/javascript-import/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.anzaan.com</link>
	<description></description>
	<lastBuildDate>Sat, 26 Jun 2010 03:29:01 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.6</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>using java style  import to include javascript  files</title>
		<link>http://www.anzaan.com/2009/05/using-java-style-import-to-include-javascript-files/</link>
		<comments>http://www.anzaan.com/2009/05/using-java-style-import-to-include-javascript-files/#comments</comments>
		<pubDate>Sat, 23 May 2009 12:27:02 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[front end]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[java style package import]]></category>
		<category><![CDATA[javascript import]]></category>

		<guid isPermaLink="false">http://www.anzaan.com/?p=43</guid>
		<description><![CDATA[Simple way to import javascript files and package using java like conventions. Allows importing single file of all files in a package.]]></description>
			<content:encoded><![CDATA[<p>I had used a function and a little bootstrapping trick to solve my problem with including files in PHP and I was happy with it.<br />
But recently while working on a project that has a heavy javascript codebase, I started having trouble managing  all javascript file imports and all those script tags made pages look really ugly.<br />
And also I really longed for java&#8217;s clas importing capabilities in javascript such that I could import a single file based on package name or I could import a whole package.<br />
Since some of the pages I&#8217;m working requires over 15 script imports, some third-party libraries and some of our own files.<br />
And importing scripts one by one suffers from latency problems as it increases page load time and can contribute to user annoyances.<br />
So I longed for  java&#8217;s style of package and class  import and  decided to try my hand on writing some script to emulate imports based on packages.</p>
<p>I jsut used the  similar principle I used with php, but the problem is importing all files in a package isn&#8217;t possible in javascript because  javascript cannot read files form disk let alone iterate through a folder and read file content.<br />
For that there was nothing I could do except use some server-side help.</p>
<p>here&#8217;s the js file code with  function for importing js file and js files contained in a package(folder).</p>
<pre class="brush: javascript;">

//create namespace to aviod any present/ future  variable/object/funciton conflicts

if (typeof Anzaan == &quot;undefined&quot; || !Anzaan) {

Anzaan = {};
}

// array to hold all imported files so as not to import them twice
Anzaan.imports = [];

//server side URL for loading whole package content
Anzaan.packageLoaderURL='/Framework/packageLoader/';

//set the base folder for importing files
Anzaan.importBase='js/';

/**
* import a class using the java naming syntax for a class name.
*@param module the module to import
*@param  config object literal with two properties-
* config.packageLoaderURL - the server url for loading all files in a folder/package as a stream
* config.importBase - the base path for importing files
* use config only if necessary otherwise just modify Anzaan.packageLoaderURL and Anzaan.importBase
* of course you can use a different namespace or just use no namespace
*/
function Import(module, config) { //com.anzaan.framework.*

if(config){
if(config.packageLoaderURL)
Anzaan.packageLoaderURL=config.packageLoaderURL;

if(config.importBase)
Anzaan.importBase=config.importBase;
}

// if this import has already happened, don't bother,
if (Anzaan.imports[module] )
return ;

var head= document.getElementsByTagName('head')[0];
var script= document.createElement('script');
script.type= 'text/javascript';

var src='';
var folders=module.split(&quot;.&quot;);
for(var i=0;i&lt;folders.length;i++){

if(folders[i].indexOf('*') &lt; 0)
src+=folders[i]+&quot;/&quot;;
}
src=src.substring(0,src.length-1);//remove the last slash

if (module.indexOf('*') &lt; 0) { //if not package import
src=Anzaan.importBase+src+&quot;.js&quot;;
script.src=src;

} else {
script.src=Anzaan.packageLoaderURL+&quot;?package=&quot;+Anzaan.importBase+src;
}

head.appendChild(script);
Anzaan.imports[module] = module;
}
</pre>
<p>The config parameter is optional. It shouldn&#8217;t really be used unless you want to load files from locations other tahn the default location of your application and want to use other URL for loading script files.</p>
<p>Just modify the global variables Anzaan.packageLoaderURL and Anzaan.importBase to set the base path and the serverside URL for loading scripts in folder.<br />
And of course rename Anzaan to something more meaningful for you.</p>
<p>Now on the server side here&#8217;s a simple php script that services the script file requests.<br />
It loads contents from js flies that reside in folder specified by &#8216;package&#8217;  variable.</p>
<p>packageLoader.php<br />
&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;</p>
<pre class="brush: php;">
&lt;?php

$folder=$_GET[&quot;package&quot;]; // get the package name

$dir = opendir($folder); //open directory

while (($file = readdir($dir)) !== false) {
if (strrpos($file, '.js')) {

echo file_get_contents($folder.'/'.$file); //printout the content of file

}
}

?&gt;
</pre>
<p>and here&#8217;s a Java Servlet for doing the same thing:</p>
<pre>JSPackageLoaderServlet.java</pre>
<pre class="brush: java;">

public class JSPackageLoaderServlet extends HttpServlet {

@Override
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {

response.setContentType(&quot;text/plain&quot;);
ServletOutputStream out = response.getOutputStream();

String packagePath = request.getParameter(&quot;package&quot;);

StringBuilder sb = new StringBuilder();

File myDir = new File(getServletContext().getRealPath(packagePath));
if (myDir.exists() &amp;&amp; myDir.isDirectory()) {
File[] files = myDir.listFiles();
for (int y = 0; y &lt; files.length; y++) {

String line = &quot;&quot;;
BufferedReader in = new BufferedReader(new FileReader(files[y]));

while ((line = in.readLine()) != null) {
sb.append(line);

}

}

}
out.print(sb.toString());
}
}
</pre>
<p>Here&#8217;s the usage:</p>
<pre class="brush: javascript;">
Import('anzaan.event.EvenHandler');
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.anzaan.com/2009/05/using-java-style-import-to-include-javascript-files/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
