1

So I don't know if this is possible, but I wanted to check for a window.OneTrust object and if it doesn't exist, to keep the attribute as src, otherwise keep it as data-src and change the type.

Here is what I'm talking about:

If window.OneTrust exists, keep it as:

<script
  type='text/plain'
  id='google-maps-api-script'
  className='optanon-category-C0004'
  data-src="https://maps.googleapis.com/maps/api/js?key=<?php echo get_field('google_maps_api_key', 'option') ?>&v=weekly"
></script>;

Otherwise, have it as:

<script
  type='text/javascript'
  id='google-maps-api-script'
  className='optanon-category-C0004'
  src="https://maps.googleapis.com/maps/api/js?key=<?php echo get_field('google_maps_api_key', 'option') ?>&v=weekly"
></script>;

Is there a way that I can have a ternary operator for type/src instead of doing it like this?

if (!window.OneTrust) {
  <script
    type='text/javascript'
    id='google-maps-api-script'
    className='optanon-category-C0004'
    src="https://maps.googleapis.com/maps/api/js?key=<?php echo get_field('google_maps_api_key', 'option') ?>&v=weekly"
  ></script>;
} else {
  <script
    type='text/plain'
    id='google-maps-api-script'
    className='optanon-category-C0004'
    data-src="https://maps.googleapis.com/maps/api/js?key=<?php echo get_field('google_maps_api_key', 'option') ?>&v=weekly"
  ></script>;
}
pilchard
  • 12,414
  • 5
  • 11
  • 23

1 Answers1

1

You can use document.write in a <script> element.

<script>
if (!window.OneTrust) {
  document.write(`<script
    type='text/javascript'
    id='google-maps-api-script'
    class='optanon-category-C0004'
    src="https://maps.googleapis.com/maps/api/js?key=<?php echo get_field('google_maps_api_key', 'option') ?>&v=weekly"
  ><\/script>`);
} else {
  document.write(`<script
    type='text/plain'
    id='google-maps-api-script'
    class='optanon-category-C0004'
    data-src="https://maps.googleapis.com/maps/api/js?key=<?php echo get_field('google_maps_api_key', 'option') ?>&v=weekly"
  ><\/script>`);
}
</script>
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
  • This is not raw HTML??? it's JSX. I'm judging by the `className` attribute. – Ruan Mendes Nov 30 '21 at 19:20
  • @JuanMendes, someone edited my question into `className`, it was HTML `class=` before. –  Nov 30 '21 at 19:39
  • Don't you need to escape the closing script tag? [Why split the – Ruan Mendes Nov 30 '21 at 19:43