Views: 6822
Last Modified: 07.04.2022

Variants for code locations

Before starting to write JS code, there is a valid question - where to store it?

There are several options:

  • When you develop JS code for component and this code isn't used in any other locations, it's recommended to place the file script.js in the template of the component itself.
  • When JS code is used generally for the complete public section, its better to allocate it within the site template. Usually, js/ subfolder stores such JS files and they are connected within the template by method: Bitrix\Main\Page\Asset::getInstance()->addJs();. However, this path is not suitable when a site has several templates or if you are redeveloping code for administrative section, or a public template update is prohibited due to being updated by Bitrix24 (For example, for Bitrix24 On-premise template).
  • The instance described above uses file storage method by the path local/file.js. Use the same method when you decide to create your own custom module.

Registering and connecting libraries

Let's examine the last option in more detail. Indeed, you can allocate the code in the site template via Bitrix\Main\Page\Asset::getInstance()->addJs();. However, more correct solution will be the third approach.

Each file within your folder is essentially an individual mini-library, which you need to register. Registering Registering libraries in the module's include.php or within init.php. is performed via the following code:

$arJsConfig = array( 
    'custom_main' => array( 
        'js' => '/bitrix/js/custom/main.js', 
        'css' => '/bitrix/js/custom/main.css', 
        'rel' => array(), 
    ) 
); 

foreach ($arJsConfig as $ext => $arExt) { 
    \CJSCore::RegisterExt($ext, $arExt); 
}

As you can see, this code is universal and you can register several files. You can additionally specify CSS file in the CSS key (in case when CSS code used jointly with JS code), and use the key rel to enumerate codes of other BX libraries which will be automatically connected when connecting this library.

When libraries have been registered, they can be connected via the following structure:

CUtil::InitJSCore(array('custom_main'));

Two blocks of code, listed above are used together and sometimes - separately. For example, when developing your own module, you need to register in the module's include.php, and initiate (call InitJSCore) in the location you need (for example, in the component template).

File merge error



Courses developed by Bitrix24