Documentation 2.x and 3.x

How to add custom JS / CSS files to your plugin?

If you are building your own website, you can add required JS and CSS directly in your theme layout file. But if you are building fully functional plugin, you need to put all required assets within it.

All plugin related JS / CSS / Image files should be in "public" folder withing plugin.

To add these files to theme, you need to create "system.php" file in your plugin root directory with following content:

<?php

namespace Modules\plugin_group\plugin_name; //namespace should be changed accordingly to your plugin module name and group


class System{ //class name can't be changed. 

    // this method will be executed on each pageview.
    // If it is not, check these things:
    // - file name should be "system.php"
    // - namespace should reflect your plugin goup and name
    // - your plugin should be installed. If your plugin appear on tab Developer -> Modules, then you are fine.
    // - Class name is "System" and method is "init"
    function init(){
        global $site;

        $site->addCss(BASE_URL.PLUGIN_DIR.'public/somefile.css');
        // this file will be printed using function echo $site->generateHead(); in your layout file. Usually ip_themes/your_theme/main.php

        $site->addJavascript(BASE_URL.PLUGIN_DIR.'public/somefile.js');
        // this file will be printed using function echo echo $site->generateJavascript(); in your layout file. Usually ip_themes/your_theme/main.php

    }
    
}

If your plugin has widgets, CSS / JS / Image files needed for those widgets should be included in the same way. And it is good practice to use one CSS and / or JS file for all widgets of one plugin if there is not significant amount of code.

All this is for website frontend. If you are creating administration tab in management area, these methods doesn't work. Administration tabs just print anything you return in manager.php file. Deal with required CSS / JS in anyway you like / need.

Write a comment

You must be logged in to comment.