Advertisement
Guest User

JS

a guest
Nov 12th, 2012
160
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.55 KB | None | 0 0
  1. <?php
  2. /* Basic solution */
  3. $js = array();
  4.  
  5. $js[] = "/path/to/js/file.js";
  6.  
  7. foreach( $js as $value )
  8. {
  9.     printf( "<script type='text/javascript' src='%s'></script>\n", $value );
  10. }
  11.  
  12. /* More complicated solution */
  13.  
  14. abstract class PageJS
  15. {
  16.     protected static $js = array();
  17.    
  18.     static public function add( $js, $type = "file", $group = "global" )
  19.     {
  20.         if( in_array( $type, array("file", "code") ) === false )
  21.         {
  22.             return false;
  23.         }
  24.        
  25.         self::$js[$group][] = array( $js, $type );
  26.        
  27.         return true;
  28.     }
  29.    
  30.     static public function display( $group = "global" )
  31.     {
  32.         if( empty( self::$js[$group] ) === true ) return false;
  33.        
  34.         foreach( self::$js[$group] as $value )
  35.         {
  36.             if( $value[1] == 'file' )
  37.             {
  38.                 printf( "<script type='text/javascript' src='%s'></script>\n", $value[0] );
  39.             }
  40.             else
  41.             {
  42.                 printf( "<script type='text/javascript>%s</script>\n", $value[0] );
  43.             }
  44.         }
  45.     }
  46. }
  47.  
  48. // Examples:
  49.  
  50. // Adding Global JS
  51. PageJS::add( "/path/to/js/file.js" );
  52. PageJS::add( "/path/to/js/file.js", "file" ); // Same thing as example above
  53. PageJS::add( "
  54.     $(function() {
  55.         alert('Document ready!');
  56.     });
  57. ", "code" );
  58.  
  59. // Displaying Global JS
  60. PageJS::display();
  61.  
  62. // Adding JS for specific groups
  63. PageJS::add( "/path/to/js/file.js", "file", "groupForCustomPage" );
  64. PageJS::add( "
  65.     $(function() {
  66.         alert('Document ready!');
  67.     });
  68. ", "code", "groupForCustomPage" );
  69.  
  70. // Displaying a custom group JS
  71. PageJS::display(); // display the global JS
  72. PageJS::display( "groupForCustomPage" ); // display the JS for specific page.
  73. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement