Friday, November 7, 2008

AjaxCSSJS - JavaScript and CSS on-demand

Ajax has converted web pages to web applications!!! I mean we don't have separate pages for doing different things. Different functionalities are done in one single page nowadays. Sometime the users don't face a new page (refresh) even when they click a navigation link, and the new content will come to the page in an Ajax manner. It is excellent for users, but it brings a new problem for developers. Any page has its own layout and functionality, naturally it needs its own CSS and JavaScript files as well. It is not rational that we load all CSS and JavaScript files in the first main page, because it is possible that the user never click on some links and never use some functionalities in the website (web app). So we must load the CSS and JavaScript files when we need them. On the other hand we won't have any chance to refresh the page, so we can not load them by adding the <link rel=STYLESHEET and <script type="text/javascript" to the head section of the document.

Ajax Islands Solution
Download AjaxCSSJS here.
You can load JavaScript and CSS files dynamically (on-demand) by means of AjaxCSSJS which is the 4th class of AjaxIslands (the 2nd and 3ed classes are not released yet!).
You can load your CSS or JavaScript files this way:


new AjaxCSSJS('css/grid.css', 'css');
new AjaxCSSJS('js/ajaxform.js', 'js');


You load a JavaScript to use it! don't you?
I mean usually you call a function or make an object after loading a JavaScript file. In this example you are going to make an AjaxForm object like this:


new AjaxCSSJS('js/ajaxform.js', 'js');
var af = new AjaxForm("frmProfile", "profile.act.php", "loader1.gif", "profileBoard");


But your second line of code will fail!
The browser try to load the ajaxform.js asynchronously! It means that the browser won't wait for the file to be loaded and will continue executing the rest of the code. So the second line which is trying to instantiate the AjaxForm will run before the file is loaded!!!
Don't worry! AjaxCSSJS class has a nice feature to solve this problem too!
You can pass a function as 3ed argument to the constructor of the class. This function will be executed as soon as the browser loads the file. So we should change the code this way:


new AjaxCSSJS('js/ajaxform.js', 'js',
function() {
var af = new AjaxForm("frmProfile", "profile.act.php", "loader1.gif", "profileBoard");
});

Don't hesitate to comment on this class.

2 comments:

Term Papers said...

I have been visiting various blogs for my term papers writing research. I have found your blog to be quite useful. Keep updating your blog with valuable information... Regards

Seven said...

to hear that :)
I continue updating my blog...
Just a little busy these days.