Code snippets for symfony 1.x

Navigation

Snippets tagged "filter javascript"

Javascript loading optimalization

Hi!

I am using a lot of hand written jscript codes due to the required behavior not found in any javascript framework. I've created my Objects in distinct files, although some of them are quite small ( <1kb ). So to make it fast, I've written a filter class that actually parses the files found in the /js directories having *.js suffix. It does not only parse them together but removes whitespaces, comments, indentations so the sum filesize gets a bit compressed. The filter also includes the final file into the response so there is no need to include any *.js ( inside /js ) in a template.

<?php
 
    class JavascriptParser extends sfFilter
    {
      public function execute($filterChain)
      {
        $filterChain->execute();
 
 
        $fp = fopen( "js/compiled.js", "w" );
 
        JavascriptParser::getJSFiles( "js", $fp );
 
        fclose ( $fp );
 
        $response = $this->getContext()->getResponse();
        $content = $response->getContent();
        if (false !== ($pos = strpos($content, '</head>')))
        {
          $html = "<script type='text/javascript' src='/js/compiled.js'></script>";
 
          if ($html)
          {
            $response->setContent(substr($content, 0, $pos).$html.substr($content, $pos));
          }
        }
 
      }
 
      public function getJSFiles( $dir, &$fp )
      {
        $hDir = opendir( $dir );
        while( ( $filename = readdir( $hDir ) ) !== false )
        {
            if ( is_dir( $filename ) )
            {
            }
            else if ( is_dir( $dir."/".$filename ) )
                JavascriptParser::getJSFiles( $dir."/".$filename, $fp );                
            else if ( strpos( $filename, ".js" ) !== false && $filename != "compiled.js" )
            {
                $tmpFile = fopen( $dir."/".$filename, "r" );
                $data = fread( $tmpFile, filesize( $dir."/".$filename ) );
 
                $data = preg_replace( "'\/\*.*?\*\/'si", "", $data  );
                $data = preg_replace( "'//.*?\n'si", "", $data );
                $data = preg_replace( "'[ \t]+'", " ", $data );
 
                fwrite( $fp, " \n".$data );
                fclose( $tmpFile );
            }
        }
        closedir( $hDir );  
      }
    }
 
?>
 

The same should be done with *.css files, since they are even smaller and loading many small files takes much more time then loading one big.

Best Regards

by Kormany Gabor on 2008-04-13, tagged filter  javascript 
(1 comment)

Automatic Javascript Include

If you're like me and prefer to code your own Unobtusive Javascript, you'll probably find this snippet handy. It will search through your project's /web/js folder for any .js files that match the current Symfony action.

For example, the snippet/new action would look for /web/js/snippet/snippet.js and /web/js/snippet/new.js, and add them to the response if either exist.

You can also define an optional subfolder within /web/js where you want the filter to look (i.e. "backend").

The Code

<?php
 
/**
 * Looks for Javascript files based on current action/module and adds them to
 * the current response object.
 * 
 * Add this filter to the end of your filter chain in filters.yml, after the 
 * execution filter:
 * 
 * <code>
 *     rendering: ~
 *     web_debug: ~
 *     security:  ~
 *     
 *     # generally, you will want to insert your own filters here
 *     
 *     cache:     ~
 *     common:    ~
 *     flash:     ~
 *     execution: ~
 *     
 *     auto_javascript_include:
 *       class: myAutoJavascriptIncludeFilter
 * </code>
 *
 * @package     Automatic Javascript Include (AJI)
 * @subpackage  filter
 * @author      Kris Wallsmith <kris [dot] wallsmith [at] gmail [dot] com>
 * @version     SVN: $Id$
 * @copyright   Have at it ...
 */
class myAutoJavascriptIncludeFilter extends sfFilter
{
    /**
     * Include external Javascript files based on last action called.
     * 
     * This kicks in on the way back down the filter chain, so we're sure to
     * catch the last action. Looks through the web/js folder for files that
     * match the naming syntax and adds them to the response. 
     * 
     * You can specify a subfolder of the web/js folder for the filter to 
     * search in app.yml.
     * 
     * @author  Kris Wallsmith <kris [dot] wallsmith [at] gmail [dot] com>
     * @see     sfConfig::get('app_aji_subfolder')
     * @param   sfFilterChain $filterChain
     */
    public function execute($filterChain)
    {
        $filterChain->execute();
 
        $sf_context  = sfContext::getInstance();
        $sf_response = $sf_context->getResponse();
        $sf_web_dir  = sfConfig::get('sf_web_dir');
 
        $module = $sf_context->getModuleName();
        $action = $sf_context->getActionName();
 
        $sub_folder = sfConfig::get('app_aji_subfolder');
        if($sub_folder && $sub_folder{0} != '/') $sub_folder = '/' . $sub_folder;
 
        $fmt = '/js%s/%s/%s.js';
 
        $mod_mod_js = sprintf($fmt, $sub_folder, $module, $module);
        $mod_act_js = sprintf($fmt, $sub_folder, $module, $action);
 
        if(file_exists($sf_web_dir . $mod_mod_js)) $sf_response->addJavascript($mod_mod_js);
        if(file_exists($sf_web_dir . $mod_act_js)) $sf_response->addJavascript($mod_act_js);
    }
}
 
?>
by Kris Wallsmith on 2007-04-24, tagged filter  javascript 
(6 comments)