girish
girish

Reputation: 305

Handlebar objects not working when linking to a script by an URL

There are 2 ways to use a script with in a script manager

  1. linking to a script by an URL
  2. manually entering in the script.

The handle bar objects don't seem to work while linking to a script by an URL but works when manually entering it. An example script is very simple as below:

console.log("{{product.id}}");

I just wanted to find a solution or a workaround to make the handlebar objects work seamlessly when the script is hosted on a CDN.

Screenshot below:

enter image description here

Upvotes: 0

Views: 511

Answers (3)

Nathan Booker
Nathan Booker

Reputation: 684

Consider using 2 scripts. One is an inline script to instantiate certain JS variables your CDN script needs, and the other is your CDN script which checks for window.your_data when it evaluates.

So your first script might be:

<script>
  window.currentProductName = "{{product.name}}";
</script>

And your CDN script will check for window.currentProductName when it evaluates.

As script order is not guaranteed within the same insertion target, it's best to put the inline script in the header and the CDN script in the footer (generally better for site speed as well).

Upvotes: 1

Tony McCreath
Tony McCreath

Reputation: 3384

When you reference a script via the URL option it is added to the page via a script tag. This means it gets loaded and run on the client side as the page loads. It would not have access to handlebars.

When you directly enter the script in the manager it is first processed server side and the result is directly placed on the pages. It does have access to handlebars.

You may want to do a combination. A manual script to gather and store the data you need, then a url script to load the main js that can access the data you stored.

You could merge them as one by having the manual script dynamically add the script tag for your external script.

Upvotes: 0

Heather Barr
Heather Barr

Reputation: 362

I'm not sure if this is what you're looking for but you should be able to accomplish this with the inject & jsContext handlebars helpers. See both here, with a 'console.log' example. https://developer.bigcommerce.com/stencil-docs/reference-docs/handlebars-helpers-reference#inject enter image description here

Upvotes: 0

Related Questions