Cross Domain Templates Using Javascript

I am currently creating a Javascript library that can be used to easily create embedded media based on the URL of a media file, and then be managed using Javascript methods and events (think of a Flash / Silverlight JW player ).

Of course, I could just dig out all the html tags from the Javascript library and send them to the browser:

function player(url) { document.write('<object type="foo"><param name="something" value="bar">' + <param name="source" value=" + url + '/></object>'); } 

But I think this is a very ugly practice that tends to create unmanaged code that cannot be read when you review it a few weeks later.

So the template solution seems to be suitable for this. I was looking for EJS because it loads templates using AJAX, so you can manage your templates in a separate file and not directly on the HTML page.

There's one gotcha with this: my library should be completely cross-domain: the library itself can be located on foo.com, and the service site can be located on bar.com. Therefore, if bar.com wants to add a media player using the library, it needs to make an AJAX call to the template located on foo.com, which will not work due to policies of the same origin in browsers.

AFAIK, there is no library that uses something like JSONP to read and write templates to work around this problem.

Can someone point me to a solution to this problem?

+4
source share
2 answers

Answering my own question: you need some kind of server-side solution that supplies JSONP to solve this problem. Let's say tou has a template on the foo.com server, you may have a server-side script that responds to such requests:

 http://foo.com/template/bar.html?callback=cb 

What will be returned:

 cb({ "html" : "<p>i'm a template!</p>" }); 

Then you can use any template language you want and analyze the template in your application.

+3
source

Very late, but I came to the conclusion that KnockOut JS is the best solution for third-party template conversion. If you upload JS to third-party web pages, Knockout allows you to enter your data into the DOM very easily without having to hold the entire HTML section as a template that you โ€œrenderโ€ (this is a paradigm that has a mustache and similar usage).

The code is simple - here is the area of โ€‹โ€‹the third party web page that you want to create:

 <p>First name: <strong data-bind="text: firstName"></strong></p> <p>Last name: <strong data-bind="text: lastName"></strong></p> 

After loading the jockout js library itself, you simply present some knockout data as a javascript model data object, and the rest:

 // This is a simple *viewmodel* - JavaScript that defines the data and behavior of your UI function AppViewModel() { this.firstName = "Bert"; this.lastName = "Bertington"; } // Activates knockout.js ko.applyBindings(new AppViewModel()); 

Literature:

0
source

Source: https://habr.com/ru/post/1305643/


All Articles