-1

Let's say I have:

<body class="hello">

How can we do something like the following?

if($("body").hasClass("hello")) {
  <script src="/demo_js/ion.rangeSlider.min.js"></script>
}

I was wondering if maybe doing something like:

if($("body").hasClass("hello")) {
 document.write('<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1.min.js"></'+'script>');
}

That looks fine but it's a mixup of jQuery and JS and I am not sure if that's the correct way anyway.

It'd be even better if this could be done via the backend in php but I am not sure how to check if an element has a class in php neither how to tell it to include a script if it does.

How would you approach it?

One trick in php I thought is the following but then again, is there any better way?

<?php
  $hello = "hello";
  if($hello) { ?>
    <script...
<?php } ?>
<body class="<?php echo $hello; ?>">
rob.m
  • 9,843
  • 19
  • 73
  • 162
  • Forget `document.write()`. Use DOM manipulation. See: https://stackoverflow.com/questions/13121948/dynamically-add-script-tag-with-src-that-may-include-document-write – Jakub Bouček Aug 07 '19 at 01:22
  • @JakubBoucek ok so are you suggesting basically to write a html element like `document.createElement('script');` and work with it's attribute src afterwards? What's the difference? – rob.m Aug 07 '19 at 01:25
  • See the linked answer in my previous comment. Difference is big one: `document.write()` you can call only when is page loadging, not later and it have more negative sife-effects. DOM access is clean. – Jakub Bouček Aug 07 '19 at 01:29
  • 1
    @JakubBoucek I see, thanks – rob.m Aug 07 '19 at 01:31
  • Possible duplicate of [How to dynamically insert a – But those new buttons though.. Aug 07 '19 at 03:29
  • why a down vote? And no it's not a duplicate, I have provided my own solution, I was asking if there was a better way or in php. – rob.m Aug 07 '19 at 20:04

1 Answers1

0

The jQuery function for this is $.getScript.

https://api.jquery.com/jQuery.getScript/

$.getScript( "/demo_js/ion.rangeSlider.min.js" )
ceejayoz
  • 176,543
  • 40
  • 303
  • 368