Saturday, March 12, 2011

Javascript Goodie - Smart Load JS/CSS Linked Files on First Ajax Request Only - Not on Subsequest Requests.

I've experienced an issue on many occasions where a feature of a website needs to load some advanced ui functionality via ajax onto a page and link additional css and/or js files with the ajax request in order to accomplish it. This feature may be requested numerous times while completing some sort of set-up, whatever. The repeated loading of the same css or js files is an unnecessary bandwidth hog and may slow the user experience considerably, as pop-up modals are expected to be snappy. In some cases this repeated reloading of the same linked files might possibly cause javascript errors as the repeated overloading of javascript functions overwriting the previous instance in the browser memory each time the js file is reloaded with the ajax request.

This is my solution. I had googled this issue on random occasions and found a couple hints here and there in the direction of what I wanted to accomplish, but no solid solutions presented themselves. So, I wrote my own solution. It was a lot simpler than I originally expected.

This example relies somewhat on jQuery, but it could be rewritten without it.

    function smartLoad(flist){
        if(flist.length==0){return false;}
        var flistArray = flist.split(',');
        for(i in flistArray) {
            var f = $.trim(flistArray[i]);
            if(window.smartLoadList.indexOf(f)==-1) {
                if(f.substr(f.length-2,2).toLowerCase()=='js') {
                    $("head").append('<scr'+'ipt src="'+f+'" type="text/javascript"></scr'+'ipt>');
                } else if(f.substr(f.length-3,3).toLowerCase()=='css') {
                    $("head").append('<li'+'nk rel="stylesheet" type="text/css" href="'+f+'" />');
                } else {
                window.smartLoadList = window.smartLoadList + "," + f;
    $(document).ready(function() {
        smartLoad("/css/custom.css, /javascript/c1.js, /javascript/c2.js");

That's a wrap!

No comments: