Skip to content

Instantly share code, notes, and snippets.

@brh55
Last active August 29, 2015 14:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brh55/1fea13ed68f646e69116 to your computer and use it in GitHub Desktop.
Save brh55/1fea13ed68f646e69116 to your computer and use it in GitHub Desktop.
Basic MODx Snippet for Selectively Adding JS or CSS
<?php
/**
Parameters:
Required:
$filePath = specify the path of the stylesheet or js file.
Optional:
&fileType = css or js
&runLocation = (default is head), user can specify ending of body tag
&preComment = String of Desired Comment to be placed before file is added
**/
//Required Parameter
$filePath = $modx->getOption('filePath', $scriptProperties);
//User specify run location
$runLocation = $modx->getOption('runLocation', $scriptProperties, 'head');
//REGEX match function to search in string
preg_match('/\.css|\.js/', $filePath, $match);
$fileType = $match[0];
$preComment = $modx->getOption('preComment', $scriptProperties);
$noComment = $modx->getOption('noComment', $scriptProperties);
$comment = $preComment;
echo $comment;
if (empty($preComment)) {
//Based on file extension define a comment
switch ($fileType) {
case '.js':
$comment = '<!--Page Specific JS File -->';
break;
case '.css':
$comment = '<!--Page Specific CSS File -->';
break;
//non-traditional extension
default:
$comment = '<!--Page Specific File -->';
break;
}
}
echo $comment;
//commentEcho Function
function commentHead() {
global $comment;
global $modx;
if (empty($noComment)) {
$modx->regClientStartupHTMLBlock($comment);
}
}
function commentBody() {
global $comment;
global $modx;
if (empty($noComment)) {
$modx->regClientHTMLBlock($comment);
}
}
//Determine runLocation, if body run JS before body
if ($runLocation == 'body') {
switch ($fileType) {
case '.js':
commentBody();
$modx->regClientScript($filePath);
break;
//Place CSS call in head, it shouldn't be placed in body
case '.css':
commentHead();
$modx->regClientCSS($filePath);
break;
}
} else {
switch ($fileType) {
case '.js':
commentHead();
$modx->regClientStartupScript($filePath);
break;
case '.css':
commentHead();
$modx->regClientCSS($filePath);
break;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment