paishin
paishin

Reputation: 258

Include scripts/styles only once in OctoberCMS

OctoberCMS has a very convenient feature that allows to inject scripts or styles using {% put scripts %} in pages or partials. The problem I am facing is that each time I include a partial that contains this it duplicates the added scripts.

Is there a feature that you can set in order to put scripts only once?

A typical use case that I am facing is with a slider partial that I only want to load its scripts and styles when its actually used in the displayed page, but if I have multiple sliders then I dont want to include the scripts multiple times.

Upvotes: 0

Views: 267

Answers (1)

Hardik Satasiya
Hardik Satasiya

Reputation: 9693

There are two solution, you can use any of them, which is well suited for you.

1. you can give your script unique id to check if its already exist or not and based on that include it

We make 2 scripts

  1. check-script will check if main script is added or not if not added add it, OR if already there skip to add.
  2. your main script

check-script.js

window.scriptIncluded = document.getElementById('script-included');

// check if script is already loaded if not include it
if(!window.scriptIncluded) {

    scriptTag = document.createElement('script');
    scriptTag.id = 'script-included'; // <- USE YOUR ID HERE ITS JUST FOR DEMO
    scriptTag.src = '/plugins/.../assets/bundle.js';

    // add script first time
    document.head.append(scriptTag);
}

now in your {% put scripts %} just include this script

{% put scripts %}
    <script type="text/javascript" src="/plugin/.../js/check-script.js"></script>
{% endput %}

yes check-script.js may be include multiple time but, it will load your main script only once.

2. better solution would be to add script from your component file and check there

public function onRun()
{    
    // if global variable is not set only then include script
    if(!isset($GLOBALS['script-included'])) { // <- USE YOUR ID HERE ITS JUST FOR DEMO

        $this->addJs('/plugins/.../assets/main-script.js');

        // set global variable so next time script will not be included
        $GLOBALS['script-included'] = true;
    }
}

if any doubt please comment.

Upvotes: 3

Related Questions