Dec 7, 2013

Loading blog modules dynamically

I just want to share a little trick that I have applied to my blog a few days ago. If you have a blog like mine, in which you talk about everything, and maybe in some of the posts you need to use a code highlighter, a math or graphics renderer, or any other kind of scrpt, but in other posts you don't need them at all, maybe you noticed for sure that loading that scripts from beginning in every page that your readers visits in your website, will slow down the page charging, and therefore will degrade the user experience in your website.
So, my idea is to load only the scripts that I need, and enable or disable them with a few minimal code. This trick can be applied to any kind of template of Blogger because the following code doesn't requires to modify it.
First at all, go to your Blogger dashboard and click on Layout and then select Add a Gadget.
Add a HTML/JavaScript gadget.

Don't write nothing in the Title box.
And in the Content box copy the following code:
<script type="text/javascript">

    // Javascript code goes here.

</script>
And inside the above code put the following one:
// List of modules to load delimited by spaces.
var blogModules = "";

// Capitalize a string.
function capitalize(string)
{
    return string.charAt(0).toUpperCase() + string.slice(1);
}

// Run a function from string.
function runFunction(name, arguments)
{
    var fn = window[name];

    if (typeof fn !== 'function')
        return;

    fn.apply(window, arguments);
}

// Load all enabled modules.
function loadBlogModules()
{
    // Split all modules by spaces.
    var modules = blogModules.toLowerCase().split(/\s+/);

    // Remove duplicates.
    modules = modules.filter(function(elem, pos, self) {
        return self.indexOf(elem) == pos;
    });

    // Run each module funtion with the form:
    //
    // blogModule[Capitalized module name]
    for (var module in modules)
        runFunction("blogModule" + capitalize(modules[module]));
}

// Load an external or embedded file.
function loadBlogFile(filename)
{
    // "blogFiles" is a hash map with the name of a file as key
    // and the base64 encoded file as value.
    if (typeof blogFiles != "undefined" && filename in blogFiles)
        // Embedded files load faster and
        // so are the prefered method.
        return blogFiles[filename];
    else
        // Load from an external source.
        return filename;
}

// Execute "func" when the website is fully loaded.
function attachOnLoad(func)
{
    if (window.attachEvent)
        window.attachEvent('onload', func);
    else
    {
        if(window.onload)
        {
            var curronload = window.onload;

            var newonload = function() {
                curronload();
                func();
            };

            window.onload = newonload;
        }
        else
            window.onload = func;
    }
}

// Append a new script or style sheet to the header and execute
// callback when the script is fully loaded.
function loadExternalfile(filetype, filename, callback)
{
    if (filetype == "js")
    {
        var fileref = document.createElement('script');

        fileref.setAttribute("type","text/javascript");
        fileref.setAttribute("src", filename);
    }
    else if (filetype == "css")
    {
        var fileref = document.createElement("link");

        fileref.setAttribute("rel", "stylesheet");
        fileref.setAttribute("type", "text/css");
        fileref.setAttribute("href", filename);
    }

    if (typeof fileref != "undefined")
    {
        if (typeof callback !== 'undefined')
            fileref.onload = callback;

        document.getElementsByTagName("head")[0].appendChild(fileref);
    }
}

// This function is useful when you need to load many scripts in
// which one script depends on each other.
function scriptChainLoad(scripts, callback)
{
    if (scripts.length == 0)
    {
        if (typeof callback !== 'undefined')
            callback();
    }
    else
    {
        function chain()
        {
            scriptChainLoad(scripts, callback);
        }

        script = scripts[0];
        scripts.splice(0, 1);
        loadExternalfile("js", loadBlogFile(script), chain);
    }
}

// Return all elements that matches "className".
function getElementsByClass(className)
{
    var matchedElements = [];
    var elements = document.getElementsByTagName("*");
    var i = 0;

    for(element in elements)
        if(elements[element].className == className)
        {
            matchedElements[i] = elements[element];
            i++;
        }

    return matchedElements;
}

// Execute module loader when the website is fully loaded.
attachOnLoad(loadBlogModules);
Finally Save and put the gadget before the post area. Now for every script that you want to execute you must add a new function with the form:
function blogModuleModule1()
{
    // Put your code here.
}

function blogModuleModule2()
{
    // Put your code here.
}

function blogModuleModule3()
{
    // Put your code here.
}

// ...
Each module function must start with blogModule followed by the name of the module capitalized. Each module will be executed after the page is fully loaded.
Then when edit a new post for your blog put this code:
<script type="text/javascript">
blogModules += " module1 module2 module3";
</script>
Or even better, got to the Blogger dashboard -> Settings -> Posts and comments -> Post Template, and copy the code there.
Thats all in the next posts I will show you some useful modules for this script

No comments:

Post a Comment