Load JS & CSS Files on Specific Pages in Drupal 7

Loading a CSS or JS file for a particular page in Drupal is a cinch with hooks. Here’s a few of the ways you can load JS & CSS on specific pages. Before you get started, I’d suggest taking a look at Drupal’s drupal_add_js and drupal_add_css. Regardless how you go about doing it, you’ll need to be somewhat familiar with these functions.

Loading a CSS or JS file for a particular page in Drupal is a cinch with hooks. Here’s a few of the ways you can load JS & CSS on specific pages. Before you get started, I’d suggest taking a look at Drupal’s drupal_add_js and drupal_add_css. Regardless how you go about doing it, you’ll need to be somewhat familiar with these functions.


Using a Module

Here’s one of the simplest methods I found to load certain JS and CSS files on specific pages. It uses a custom module and Drupal’s request_uri to define when scripts should get loaded.

function modulename_init() {
  if (request_url() == 'your-url-path') {
    drupal_add_js( /* parameters */ );
    drupal_add_css( /* parameters */ );
  }
}

Using a Template Preprocess

You can also use Drupal’s preprocess functions to add JS and CSS to specific pages:

In your template.php:

template_preprocess_node

function yourtheme_preprocess_node(&$vars) {
  // Add JS & CSS by node type
  if( $vars['type'] == 'your-node-type') {
    drupal_add_js( /* parameters */ );
    drupal_add_css( /* parameters */ );
  }
  
  // Add JS & CSS to the front page
  if ($vars['is_front']) {
    drupal_add_js( /* parameters */ );
    drupal_add_css( /* parameters */ );
  }
  
  // Add JS & CSS by node ID
  if (drupal_get_path_alias("node/{$vars['#node']->nid}") == 'your-node-id') {
    drupal_add_js( /* parameters */ );
    drupal_add_css( /* parameters */ );
  }
}

template_preprocess_page

function yourtheme_preprocess_page(&$vars) {
  // Add JS & CSS by node type
  if (isset($vars['node']) && $vars['node']->type == 'your-node-type') {
    drupal_add_js( /* parameters */ );
    drupal_add_css( /* parameters */ );
  }
}

template_preprocess_views_view

function template_preprocess_views_view(&$vars) {
  // Get the current view info
  $view = $vars['view'];

  // Add JS/CSS based on view name
  if ($view->name == 'view_name') {
    drupal_add_js( /* parameters */ );
    drupal_add_css( /* parameters */ );
  }

  // Add JS/CSS based on current view display
  if ($view->current_display == 'current_display_name') {
    drupal_add_js( /* parameters */ );
    drupal_add_css( /* parameters */ );
  }
}

Not comfortable diving into code?

Here’s a couple of Drupal projects that allow you to inject CSS and JS into your pages:

And of course, you can use a combination of the above to add your JS and CSS files to a page. If you do it a different way or know a better Drupal way, please comment below and let me know!

PHP Stock Market API

Here’s a quick API script I put together to help monitor my stocks. It’s a PHP Stock Market API that uses the Yahoo! Finance API and allows you to retrieve up to 20 current data points for a particular symbol. It’s simple to use and doesn’t require any knowledge on how to implement or use the Yahoo! Finance API.

Looking to grab the latest stock market data? There’s a surprising lack of stock market APIs out there and even fewer that work consistently or affordable. Never fear, the PHP Stock Market API is here!

The PHP Stock Market API is a simple PHP class that uses the Yahoo! Finance API allowing you to retrieve up to 20 current data points for a particular symbol. It’s simple to implement and doesn’t require you to learn how to use the Yahoo! API.

UPDATE (Nov. 28, 2014, v1.3): getData now allows an array to pull multiple stocks at once (thanks @d3vit).
UPDATE (Jan. 27, 2014, v1.2): You can now also retrieve historical data (open, high, low, close, volume & adjusted close).

Download Now (Version 1.3) Fork on GitHub


PHP Stock Market API Usage

With just a few lines of code, you can easily retrieve 20 current data points. Here’s how it works:

<?php
require_once('class.stockMarketAPI.php');
?>

<h1>Current Stock Information for AAPL</h1>

<?php
$StockMarketAPI = new StockMarketAPI;
$StockMarketAPI->symbol = 'AAPL';
?>
<pre><?php print_r($StockMarketAPI->getData());?></pre>

<?php
$start = '01-01-2013';
$end = '01-07-2013';
?>
<h1>Historical Stock Information for AAPL (<?php echo $start ?> - <?php echo $end ?>)</h1>
<?php
$StockMarketAPI = new StockMarketAPI;
$StockMarketAPI->symbol = 'AAPL';
$StockMarketAPI->history = array(
  'start'    => $start,
  'end'    => $end,
  'interval' => 'd' // Daily
);
?>
<pre><?php print_r($StockMarketAPI->getData());?></pre>

<hr>

<h1>Stock Information for AAPL, MSFT, GOOGL</h1>
<?php
$StockMarketAPI = new StockMarketAPI;
$StockMarketAPI->symbol = array('AAPL', 'MSFT', 'GOOGL');
?>
<pre><?php print_r($StockMarketAPI->getData());?></pre>

Mozscape API PHP Class

Mozscape’s API is a little daunting to use with the amount of valuable information it can offer. Here’s a simple PHP class that allows you to easily access your site’s SEO metrics using the Mozscape API. A major benefit to the Mozscape API PHP Class is the ability to return detailed information on the response fields Mozscape provides.

Features

Download Now (Version 1.1) Fork on GitHub


Implementation

It’s pretty simple to use this class. Currently it’s pretty limited to the data it can provide in relation to what’s available through Mozscape’s API, but I do have plans on adding the rest of the available APIs later on.

That’s it, pretty simple huh?

Documentation

Here’s more detailed information on how to use the class. If you have any questions or suggestions, I’d love to hear them.

Mozscape URL Metrics API

urlMetrics($site_url, $sum_of_bit_flags)

To access the Mozscape URL Metrics API, you just need to provide the URL you want to retrieve data for and the type of data you want (the total sum of Bit Flags).

Mozscape Response Fields

responseFields($field, $return_value = '')

This is a great helper to get information on the various response fields that the Mozscape API provides, including the bit flag values, user-friendly names, slugs, and descriptions! See more information on Mozscape’s Response Fields here: http://apiwiki.seomoz.org/response-fields.

Mozscape Top Pages API

topPages($url, $offset = 0, $limit = 1000, $bits = 4)

This paid call returns the metrics about many URLs on a given subdomain. The top pages call can be accessed by the API call top-pages. A set of metrics can be requested by indicating them as bit flags in the $bits parameter. A page of urls with associated metrics is returned. The start record of the page can be specified using the $offset parameter. The size of the page can by specified using the $limit parameter. URLs are currently sorted by number of linking root domains.

A maximum of 1000 records can be retrieved per call. Limits over this value will result in a 400 Bad Request or 500 Internal Error response.

Currently only 10,000 pages may be retrieved using top-pages calls, in at least 10 calls.

See more on Mozscape’s Top Pages API here: http://apiwiki.seomoz.org/top-pages-api

Mozscape Required Attribution Link

attributionLink($type, $size, $img_dir = 'img/mozscape/')

This is good to use to stay compliant with the required Mozscape API’s attribution links. Provides easy output using their approved logo or icon with the required link.


Change Log

Version 1.1

  • Created a changelog file
  • Added an error message if the Curl request to the Mozscape API failed
  • Added the Mozscape Metadata API Calls
  • Added the Mozscape Top Pages API

Interaction Points jQuery Plugin

Trying to come up with a fun way to keep user’s on your site? Try the Interaction Points jQuery plugin. It’s a simple script that enables a point system for your site’s users. It’s fully customizable and is easily integrated into existing point systems. There’s nothing like a little competition to keep people engaged and coming back to your site.

This is also great from and SEO perspective to boost your site’s CTR and decrease its bounce rate. It will keep your users active while they surf and is perfect for gaming sites and other user interactive sites.

Features

  • Allows you to customize your own script to handle storing and processing user points
  • Users only occur points when their actually doing something
  • Set how many points the user earns each second while being active on the site
  • Allows additional data to be passed to your script
  • Includes a debugging feature to help you track down problems
  • Control how often the script get’s pinged to update user points

Download Now (Version 1.0) Fork on GitHub

Implementation

It’s simple to integrate. Just include the JS and modify the script that handles the post information to suit your site’s needs.

Here’s a sample PHP script you can use as a template to create your own:

I haven’t had a chance to throughly test it in all browsers, but don’t foresee any problems. If you run into any, let me know and I’ll get it fixed and updated. Let me know what you think!