Search code examples
javascriptphpechovbulletin

Add stylesheet/script if not added PHP & Javascript


I don't even know where to begin attempting this, what I'm trying to do is only load a file once, since I have multiple instances of it currently.

I load the files in with php, the if conditions are just whether the option is on or another.

if ($vbulletin->options['drc_fa_adm'] & $vbulletin->options['drc_fa_prov'] != 0){
  if ($vbulletin->options['drc_fa_prov'] == 1) {
    echo '<link rel="stylesheet" href="'.$vbulletin->options['bburl'].'/drc/dirty-core/libs/font-awesome/css/font-awesome.min.css">';
  }
  if ($vbulletin->options['drc_fa_prov'] == 2) {
    echo '<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.1/css/font-awesome.min.css">';
  }
}

if ($vbulletin->options['drc_jq_prov'] == 1) {
  echo '<script src="'.$vbulletin->options['bburl'].'/drc/dirty-core/libs/jquery/jquery.min.js"></script>';
} else {
  echo '<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>';
}

echo '<script src="../drc/dirty-core/libs/jscolor/jscolor.min.js"></script><script src="../drc/dirty-core/js/twit_adm.js"></script>';

this all hooks into a specific hook that some pages (not all) have multiple instances of, which cause all of them to be added 2,3 or more times.

How can I check to see if they're already on the page, and if they are to not echo them again?

I think something like this could work I just don't know how I can add it to my PHP

<script type="text/javascript">
  if(typeof jQuery == 'undefined'){
    document.write('<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></'+'script>');
  }
</script>

Solution

  • Try this:

    $alreadyLoaded = array('css' => false, 'jquery' => false);
    if ($vbulletin->options['drc_fa_adm'] & $vbulletin->options['drc_fa_prov'] != 0){
      if ($vbulletin->options['drc_fa_prov'] == 1 and !$alreadyLoaded['css']) {
        echo '<link rel="stylesheet" href="'.$vbulletin->options['bburl'] .
        '/drc/dirty-core/libs/font-awesome/css/font-awesome.min.css">';
        $alreadyLoaded['css'] = true;
    }
    if ($vbulletin->options['drc_fa_prov'] == 2 and !$alreadyLoaded['css']) {
        echo '<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.1/css/font-awesome.min.css">';
        $alreadyLoaded['css'] = true;
        }
    }
    
    if ($vbulletin->options['drc_jq_prov'] == 1 and !$alreadyLoaded['jquery']) {
        echo '<script src="'.$vbulletin->options['bburl'].'/drc/dirty-core/libs/jquery/jquery.min.js"></script>';
        $alreadyLoaded['jquery'] = true;
    } else if (!$alreadyLoaded['jquery']) {
        echo '<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>';
        $alreadyLoaded['jquery'] = true;
    }