Skip to content
Advertisement

Stencil – How to get CDN links from javascript

I’m working with Big Commerce’s stencil to add some advanced functionality to my product pages. Part of this functionality requires files to be loaded from the server. Each product page would need a different file so I can’t just use {{cdn …}} in the template file, I need the equivalent of that in javascript

Template File: {{cdn "mydogpicture.jpg"}} outputs www.cdn.bigcommerce.com/some/link/mydogpicture.jpg

I need something like var linkToDogPicture = loadFileFromServer("mydogpicture.jpg"); so then I could use that link to load the file where I need it (It wouldn’t always be a picture file)

Any ideas?

Advertisement

Answer

I’ve asked this on both Stackoverflow and the BigCommerce forums and there doesn’t seem to be a cleaner solution so I’ll go ahead and post my work around as the answer. Defining the CDN links in the custom fields doesn’t work for two reasons: The files needed aren’t known until the javascript loads a configuration json file from the server and I want to make sure the end user is getting the cdn link pointing to the server closest to them to take advantage of CDN. Here’s how I’m doing it:

  1. Upload a file to the root of your /content directory. This file can be blank, you just need to know the name of it and never change the name. In my case, I called it cdn.json

  2. In your template file use

<span id="cdn_link" style="display: none">{{cdn "cdn.json"}}</span>

to put the CDN link to cdn.json in an invisible span on the page. The cdn function should output something like httpx://cdnX.bigcommerce.com/xxxxxx/cdn.json

  1. In javascript, get the innerhtml of the span and remove cdn.json

var cdnLink = $("#cdn_link").html(); cdnLink = cdnLink.replace("version.json", "");

Now you can append paths to cdnLink to load files from the CDN server BigCommerce chooses as the fastest for the user

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement