Answers.Body: <p>I've wrapped it with try / catch</p>
  <pre><code>try {
    CRM.$(function ($) {
    )(CRM);
  } catch (e) {}
  </code></pre>
  
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2021-03-02T11:10:24.263Z
Answers.LastActivityDate: 2021-03-02T11:10:24.263Z
Answers.UserDisplayName: Interlated
Answers.Body: <p>I would recommend to <a href="https://docs.civicrm.org/dev/en/latest/extensions/" rel="nofollow noreferrer">create a CiviCRM extension</a> that implements either the <a href="https://docs.civicrm.org/dev/en/latest/hooks/hook_civicrm_pageRun/" rel="nofollow noreferrer">pageRun</a> or <a href="https://docs.civicrm.org/dev/en/latest/hooks/hook_civicrm_buildForm/" rel="nofollow noreferrer">buildForm</a> hook, which then checks which page you are on and loads the JavaScript file.</p>
  <p>If your JavaScript needs to check for special variables or other data, it will be easier to use <code>addVars</code> to load the variable correctly, instead of relying on DOM hacks.</p>
  <p>Otherwise I guess you could check if:</p>
  <pre><code>if (typeof CRM != 'undefined') {
    // ...
  }
  </code></pre>
  
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2023-07-20T19:54:00.673Z
Answers.LastActivityDate: 2023-07-20T19:54:00.673Z
Answers.UserDisplayName: bgm
Body: <p>I'm trying to load a civicrm function. What is the recommended way to load 'CRM' checking that it is available on the page first?</p>
  <pre><code>CRM.$(function ($) {
    'use strict';
  
     ...
  
    addObserverFormErrors();
  })
  </code></pre>
  
Tags: <javascript>
Title: How do I load javascript only on pages with CiviCRM loaded on them?
ThreadText: # How do I load javascript only on pages with CiviCRM loaded on them?
  
  (Asked by: username_0 on 2021-03-02)
  
  I'm trying to load a civicrm function. What is the recommended way to load 'CRM' checking that it is available on the page first?
  CRM.$(function ($) {
    'use strict';
  
     ...
  
    addObserverFormErrors();
  })
  
  **Tags:** javascript
  
  
  ---
  
  ## 2 answers
  
  ### Answer by username_0 on 2021-03-02. Score: 0 | Accepted answer
  
  I've wrapped it with try / catch
  try {
    CRM.$(function ($) {
    )(CRM);
  } catch (e) {}
  
  
  ---
  
  ### Answer by username_1 on 2023-07-20. Score: 1
  
  I would recommend to create a CiviCRM extension that implements either the pageRun or buildForm hook, which then checks which page you are on and loads the JavaScript file.
  If your JavaScript needs to check for special variables or other data, it will be easier to use addVars to load the variable correctly, instead of relying on DOM hacks.
  Otherwise I guess you could check if:
  if (typeof CRM != 'undefined') {
    // ...
  }
  
  
  ---
  
  