CodeIgniter Forums

Full Version: jLoad - Javascript loader library
You're currently viewing a stripped down version of our content. View the full version with proper formatting.

El Forum

[eluser]fatnic[/eluser]
OK. Not sure if this has been done before but here it is anyway. jLoad is basically a library to help load required javascript files quickly into a view.

You can download the zip here

First you need the jLoad config file. Here is where you set the path to your javascript files, set autoloading files and groups of files.
Code:
// Javascript path
$config['javascript_path'] = base_url().'js/';
// Files to autoload when library loaded
$config['javascript_autoload'] = array('jquery-1.2.6.pack');
// Groups of files for quick loading
$config['jload_img_zoom'] = array('jquery.fancybox-1.0.0', 'image_zoom');

Then to use the library ensure you place the following in the head of your view file.
Code:
<?php if (isset($javascript)) echo $javascript; ?>

Then in your controller you can use
Code:
// Load the library (autoloading scripts added)
$this->load->library('jload');
// Add a single (or list) of scripts
$this->jload->add('script1', 'script2');
// Or an array
$this->jload->add(array('script1', 'script2'));
// Or add a defined group with one call
$this->jload->group('img_zoom');
// then generate the script tags
$data['javascript'] = $this->jload->generate();

Now all the required script tags will automatically be inserted into your view.

Anyway, like I said, this has probably been done before but it's something I needed and cooked up quickly. Thought I would share. Smile

Feel free to comment or suggest some ways to make it better. I've not been using CI long and could do with some tips.

Cheers.

El Forum

[eluser]Bramme[/eluser]
it's a nice thing, but your library's purpose alone has been covered in the Colin Williams' template library, which I like a lot.

I personally think people who would need something like this, would already use some sort of template library and thus not really need it...

Nice job none the less!

Edit: one little idea: make sure your $javascript variable is an empty string when the library's loaded but no js files, that way, people don't have to use the isset() part.

El Forum

[eluser]fatnic[/eluser]
Wow. That's a pretty useful template library! I've just scanned the user guide and it looks very comprehensive.

I've taken on-board your comment about the $javascript variable too.

Thanks for your input. Much appreciated.

El Forum

[eluser]Sarre[/eluser]
Hi,

I've changed it a bit to allow for dynamically loading scripts.
If you have a javascript-heavy site, this will append the scripts to the dom. It makes the site "feel" faster, as you can start surfing as soon as the dom is loaded, and before the scripts are loaded.

The library:

Code:
<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

/**
* CodeIgniter
*
* An open source application development framework for PHP 4.3.2 or newer
*
* @package        CodeIgniter
* @author        Rick Ellis
* @copyright    Copyright (c) 2006, EllisLab, Inc.
* @license        http://www.codeignitor.com/user_guide/license.html
* @link        http://www.codeigniter.com
* @since        Version 1.0
* @filesource
*/

// ------------------------------------------------------------------------

/**
* CodeIgniter JLoad v1.0
*
* This library lets you specify what Javascript files to include in your view.
*
* - Filenames can be passed as either an array
*                 $this->jload->add(array('script1', 'script2'));
*      or individually.
*                 $this->jload->add('script1', 'script2');    
*   you can also add a group defined in the jload config
*                 $this->jload->group('group_name');  
*   Then the tags are built with
*                 $data['javascript'] = $this->jload->generate();
*      
*
* @package        CodeIgniter
* @subpackage    Libraries
* @category    Javascript Loader
* @author        Dave Nicholson
* @link        http://www.davenicholson.co.uk/
*/

/**
* Jload
*
* @package CodeIgniter
* @author
* @copyright 2008
* @version $Id$
* @access public
*/
class Jload
{

    var $javascript_path;
    var $javascript_files;
    var $CI;
    var $dynamic;


    /**
     * Jload::Jload()
     *
     * @return
     */
    function Jload()
    {

        // Get CodeIgniter instance
        $this->CI = &get;_instance();
        // Load JLoad config file
        $this->CI->load->config('jload');
        // Get Javascript path
        $this->javascript_path = $this->CI->config->item('javascript_path');
        // Load dynamically?
        $this->dynamic = $this->CI->config->item('javascript_dynamic');
        // Clear files array
        $this->clear();

        // Get autoload javascipt files
        $autoload_javascript = $this->CI->config->item('javascript_autoload');
        if ($autoload_javascript) {
            $this->add($autoload_javascript);
        }

    }

    /**
     * Jload::add()
     *
     * Add a single or array of javascript filenames
     * @param mixed $files
     * @return
     */
    function add($files)
    {
        // If $files is an array
        if (is_array($files)) {
            // Add each one to javascript_files
            foreach ($files as $file) {

                if (!in_array($file, $this->javascript_files)) {
                    $this->javascript_files[] = trim($file);
                }
            }
        } else {
            // Loop through passed params
            for ($i = 0; $i < func_num_args(); $i++) {

                if (!in_array(func_get_arg($i), $this->javascript_files)) {
                    $this->javascript_files[] = trim(func_get_arg($i));
                }
            }
        }
    }
  
  /**
   * Jload::group()
   *
   * Add a grouped list of file names from the jload config file
   * @param mixed $group
   * @return void
   */
    function group($group) {
        
        $this->add($this->CI->config->item('jload_'.$group));
        
    }

    /**
     * Jload::generate()
     *
     * Return HTML script tags with javascript file src elements
     *     - $no_tags = TRUE just returns array of added filenames  
     * @param bool $no_tags
     * @return
     */
    function generate($no_tags = false)
    {
        // Clear output
        $output = "";
        
        if($this->dynamic) {

            $output = "&lt;script type=\"text/javascript\"&gt;";
            $output .= "\nfunction loadJS(url) {";
            $output .= "\n  var e = document.createElement(\"script\"); e.src = url; e.type=\"text/javascript\";";
            $output .= "\n  document.getElementsByTagName(\"head\")[0].appendChild(e);";
            $output .= "\n}";
            $output .= "\nonload = function() {";
    
            if (!$no_tags) {
                // Loop through files and output script tags
                foreach ($this->javascript_files as $file) {
    
                    $output .= "\n  loadJS(\"{$this->javascript_path}{$file}\");";
    
                }
                
                $output .= "\n}";
                $output .= "\n&lt;/script&gt;";
    
            } else {
    
                return $this->javascript_files;
    
            }

        } else {

            if (!$no_tags) {
                // Loop through files and output script tags
                foreach ($this->javascript_files as $file) {
    
                    $output .= "&lt;script type=\"text/javascript\" src=\"{$this->javascript_path}{$file}\"&gt;&lt;/script&gt;\n";
    
                }
    
            } else {
    
                return $this->javascript_files;
    
            }
        
        }
        
        
        
        return $output;

    }
    
    /**
     * Jload::clear()
     *
     * Clears javascript_files array
     * @return
     */
    function clear()
    {

        $this->javascript_files = array();

    }

}
?&gt;

In the config file, just add:
Code:
$config['javascript_dynamic'] = true;

Greetz

El Forum

[eluser]Jamie Rumbelow[/eluser]
Nice, but what might be a good idea would be to include a library function that does all the conditionals and outputs the html. Otherwise, simple idea executed well!

Cool!