Dynamic script injection not working with innerHTML

I’m trying to dynamically insert a booking widget into my page using innerHTML when a user clicks a button, but the script part isn’t executing properly.

My current approach:

const widgetHTML = `
<div class="booking-widget-container" data-booking-url="https://example-booking.com/user123/meeting" style="min-width:300px;height:600px;"></div>
<script type="text/javascript" src="https://example-booking.com/js/embed.js" async></script>
`;

function displayBookingWidget() {
  document.getElementById("widget-container").innerHTML = widgetHTML;
}

When I test this by putting regular text content between the div tags instead of the script, the text shows up fine. This tells me the DOM manipulation itself is working correctly. However, when I include the script tag for the booking widget, nothing appears on the page.

What could be preventing the script from loading when inserted via innerHTML?

Browsers often block script tags added via innerHTML for security purposes. I encountered this issue last year while trying to add a booking widget myself. A couple of ways to resolve this are: First, you can set your innerHTML and then create a script element using document.createElement('script'), set the src to your embed URL, and append it to the container or document head. This method ensures the script executes. Alternatively, consider loading embed.js once when the page loads and then simply use innerHTML for the div, followed by calling any required initialization function for the widget. This approach is more efficient as it avoids repeated script loading.