Lazy load github gist files to display source code on the website - gist

I have a couple of gists which I need to include in a website post to showcase the source code. Currently, I'm inlining each of the multiple gists at various places in the HTML with script tags, however, this would be a blocking call. So, is there a way to dynamically load the gists and paste it specific points in time.
I tried something like below :-
<html>
<body>
<div id="bookmarklet_1.js"></div>
<div id="bookmarklet_2.js"></div>
<div id="bookmarklet_3.js"></div>
var scriptMap = {'bookmarklet_1.js' : 'https://gist.github.com/892232.js?file=bookmarklet_1.js',
'bookmarklet_2.js' : 'https://gist.github.com/892234.js?file=bookmarklet_2.js',
'bookmarklet_3.js' : 'https://gist.github.com/892236.js?file=bookmarklet_3.js'};
var s, scr, holder;
for(s in scriptMap){
holder = document.getElementById(s);
scr= document.createElement('script');
scr.type= 'text/javascript';
scr.src= scriptMap[s];
holder.appendChild(scr);
}
</script>
</body>
</html>
The above didn't work for me, it seems that each script is doing a document.write internally to write the CSS and soure code. Has anyone tried this before or got it working ?

I started a project exactly for this purpose. Dynamically-embedded Gists
Try it now: http://urlspoiler.herokuapp.com/gists?id=992729
Use the above url as the src of a dynamically-created iframe, or add &format=html to get the Gist html snippet via ajax, then put it anywhere you want. (The gist in the above url also happens to be the documentation for how to use this project.)

I myself wanted to do exactly the same thing (with the addition of even removing the default gist style link) - ended up building a "generic" script loader that handles document.write calls :
https://github.com/kares/script.js
Here's how one can use it for embedding gists (and pasties) :
https://github.com/kares/script.js/blob/master/examples/gistsAndPasties.html

You can now get the HTML + CSS directly using JSONP.
I wrote a fuller answer in response to this question, but the key is that you can get the HTML + CSS using JSONP.
For example: https://gist.github.com/anonymous/5446989.json?callback=callback12345
callback12345({
"description": "Function to load a Gist without an iframe",
"public": true,
...
"div": <HTML code>,
"stylesheet": <URL of CSS file>
})

Related

How do I load an ejs template file into my HTML?

I am using EJS in the browser (not on the server).
I have some ejs that I would like to use in multiple pages, so I want to put that in its own file, say table.ejs.
Is there a way I can include it in my HTML such that it is immediately accessible to my javascript after onload?
I was thinking something like:
<script id="table-ejs" type="text/ejs" src="ejs/table.ejs"></script>
then in my javascript:
ejs.render(document.querySelector('#table-ejs').???, data)
Is this possible?
I could use the Fetch API to retrieve the ejs file but then I would need to rewrite a lot of code to make it async. I was wondering if I could avoid that.
Well,
place all your ejs-files within a file "views" - within your views you can create another file "partials" - in this file you place your header and footer.ejs.
Within, lets say, your home.ejs you have to include the following code:
<%- include('partials/header'); -%>
// the rest of your code
<%- include('partials/footer'); -%>
You can find more here: https://ejs.co/#docs

Relative links in tvml?

Is it possible to use relative links in tvml? I've never had a problem using them in a webpage but just can't get it to work in my tvml docs.
From my swift:
static let TVBaseURL = "http://localhost:9001/"
This currently works from my tvml which is located at http://localhost:9001/templates/home.xml
<lockup onselect="getDocument('templates/Featured.xml')">
<img src="http://localhost:9001/graphics/icons/ICON_featured.png" width="313" height="600" />
</lockup>
Note that the onselect link is relative and works fine. However this doesn't work...
<lockup onselect="getDocument('templates/Featured.xml')">
<img src="../graphics/icons/ICON_featured.png" width="313" height="600" />
</lockup>
It all depends on how you define YOUR getDocument function. But from your code, most likely it looks a bit like this one from the official TVML Programming Guide, sec 8-3.
function getDocument(extension) {
var templateXHR = new XMLHttpRequest();
var url = baseURL + extension;
loadingTemplate();
templateXHR.responseType = "document";
templateXHR.addEventListener("load", function() {pushPage(templateXHR.responseXML);}, false);
templateXHR.open("GET", url, true);
templateXHR.send();
}
Which uses a pre-set baseURL like your code does. Thus, your get document support relative links. (and not universal link. putting the full http://localhost:9001/index.xml will break it.)
in this example, the XMLHttpRequest object open function, takes the full url, not the relative one. Read more about XMLHttpRequest open here.
In short. Nothing is relative here.
However, you can do something similar with the power of Javascript.
When you get a hold of the XML document, you can find all the tag with document.getElementsByTagName("img"), which give you a list of the image element. Then all it is left to do it to look at each of them with .item(i), get their source attribute by .getAttribute('src'), see if it start with http or https, and if not, set the new one by .setAttribute('src', baseUrl+imagePath)

What am I missing for this CQ5/AEM URL rewriting scenario?

I basically want short URLs to get resolved and HTML pages to be generated with short URLs for a CQ5 website. So far short URLs are getting mapped to long URLs as expected, but links in the generated HTML pages are not getting shortened.
For example, I am expecting the src attribute of the following <script> tag:
<script type="text/javascript" src="/content/foo/c0/06/9d/3d93a858-efb4-4619-8f9e-5edc65d0f5ae/style/clientlibs.1395978029951.js"></script>
To be shortened to:
<script type="text/javascript" src="/style/clientlibs.1395978029951.js"></script>
But it is not and remains intact. href attributes in anchor elements are not getting shortened either.
In JCR, the website is stored under /content/foo/c0/06/9d/3d93a858-efb4-4619-8f9e-5edc65d0f5ae/ and I have configured my /etc/hosts and Apache config files to make it accessible via http://site-1:4503 in my local development environment.
I have defined the following URL mappings:
{
"jcr:primaryType":"sling:Folder",
"http":{
"jcr:primaryType":"sling:Folder",
"site-1.4503":{
"sling:internalRedirect":[
"/content/foo/c0/06/9d/3d93a858-efb4-4619-8f9e-5edc65d0f5ae"
],
"jcr:primaryType":"sling:Mapping",
"redirect":{
"sling:internalRedirect":[
"/content/foo/c0/06/9d/3d93a858-efb4-4619-8f9e-5edc65d0f5ae/$1",
"/$1"
],
"jcr:primaryType":"sling:Mapping",
"sling:match":"(.+)$"
}
},
"site_1.4503":{
"sling:internalRedirect":[
"/content/foo/c0/06/9d/3d93a858-efb4-4619-8f9e-5edc65d0f5ae/home.html"
],
"jcr:primaryType":"sling:Mapping",
"sling:match":"site-1.4503/$"
}
}
}
When I test this mapping in JCR Resolver (http://localhost:4503/system/console/jcrresolver), it is working as expected. For example,
/content/foo/c0/06/9d/3d93a858-efb4-4619-8f9e-5edc65d0f5ae/style/clientlibs.1395978029951.js
is mapped to
http://site-1:4503/style/clientlibs.1395978029951.js
and
http://site-1:4503/style/clientlibs.1395978029951.js
is resolved to:
JcrNodeResource,
type=cq:ClientLibraryFolder,
superType=null,
path=/content/foo/c0/06/9d/3d93a858-efb4-4619-8f9e-5edc65d0f5ae/style/clientlibs
Also when I go to http://site-1:4503/style/clientlibs.1395978029951.js in my browser, the JS file is rendered as expected.
However when I view the HTML source for the home page, as I mentioned earlier, none of the long URLs are rewritten to their shortened forms.
Any ideas what am I missing here?
By default, CQ rewrites links in a, area and form tags. If you'd like to rewrite also paths in script tag, open OSGi configuration for LinkCheckerTransformerFactory service on publish and add following string to the Rewrite Elements option:
script:src
BTW: /content is not the best place for storing clientlibs. Usually we put this stuff in /etc/designs/YOUR_APP.
We finally managed to pinpoint the issue and fix this.
Somebody had added a com.day.cq.rewriter.linkchecker.impl.LinkCheckerImpl.xml under /apps/myapp/config.publish with the following content:
<?xml version="1.0" encoding="UTF-8"?>
<jcr:root xmlns:sling="http://sling.apache.org/jcr/sling/1.0" xmlns:jcr="http://www.jcp.org/jcr/1.0"
jcr:primaryType="sling:OsgiConfig"
service.bad_link_tolerance_interval="{Long}48"
service.check_override_patterns="[^.]"
service.special_link_patterns=".*
"
service.special_link_prefix="[javascript:,data:,mailto:,#,<!--,${]"/>
I think the combination of check_override_patterns and special_link_patterns had disabled link shortening.
Removing this file made link shortening work again.

Getting the emberjs starter-kit to work with coffeescript

i'm trying to get the starter-kit example of ember.js to work directly with an app written in coffeescript (with the use of http://coffeescript.org/extras/coffee-script.js).
I want to use this in an development environment, without the need to convert the coffescript to javascript first (manually or with tools like jitter).
Basically i just replaced the line
<script src="js/app.js"></script>
with the lines
<script src="js/libs/coffee-script-1.3.3.min.js"></script>
<script type="text/coffeescript" src="coffee/app.coffee"></script>
in the index.html
All changes i've made can be found in my fork on github at https://github.com/GordonSchmidt/starter-kit
The coffescript itself seems to be fine, because when i convert it to javascript first the starter-kit application works with this javascript. But when i use the coffeescript directly it throws the error "assertion failed: Unable to find view at path 'App.MyView'" in line 45 of ember-0.9.8.1.js. The coffee-script.js all by itself seems to work as well (see demo.html). So it has to be a conflict between ember.js and coffee-script.js.
But I'm not able to find this error. Can someone please point me in the right direction?
from coffeescript.org
The usual caveats about CoffeeScript apply — your inline scripts will
run within a closure wrapper, so if you want to expose global
variables or functions, attach them to the window object.
your coffeescript should look something like this:
<script type="text/coffeescript">
window.App = App = Em.Application.create()
App.MyView = Em.View.extend(
mouseDown: -> window.alert "hello world!"
)​
</script>
see here for a fiddle

How do autocomplete suggestions work?

For example, if you type something in upper-right google/yahoo search box in firefox there will be some kind 'suggested auto complete' sort of thing.
Another example is in youtube search box and Stackoverflow tags edit box just below this question preview. How do they work? What technology behind 'em?
What technology behind 'em?
In case you are wondering which data structure is being used underneath then its called "trie" and for using less space compared to tries you can use "DAFSA"
How do they work?
both are implemented as a tree, where each node of tree corresponds to one character in a string and the character which appears before is parent of character which appears later e.g. The strings "tap", "taps", "top", and "tops" stored in a Trie (left) and a DAFSA (right),so as you begin to type tap..the tree is traversed based on the characters typed and shows the suggestions based on some weight assigned to each word, weight may be assigned based on usage frequency of the word.
Looking up string in worst case is O(m) time where m is the length of string.
Image is being referenced from the wikipedia articel : DAFSA,trie
That's done with the use of AJAX, this site has a nice tutorial on it:
AJAX Suggest Tutorial, and the WaybackMachine version, as website seems down.
A database with keywords and a bit of code is all there is to it as far as I know.
I'm learning how to use it right now actually, for work. :)
Another resource is w3schools. They have covered it as well.
They use JavaScript to normally:
Look at a local array of all possible values
Request another page (i.e. /autocomplete.php?q=partialText) in the background.
Call a webservice.
When the JavaScript has the list of entries to show it modifies the page to show the autocomplete box.
If you want to put an autocomplete box on your website I have used and found the following to be very good. It is also based on the popular jQuery framework.
jQuery autocomplete plugin
It's quite simple.
Client side:
Grab keystrokes in form field
On keystroke make an AJAX request to server
If another keystroke is entered immediately, cancel current AJAX request as it is obsolete now
Make a new AJAX requested with updated characters in form field
Show server response to client
Server side:
All words are already bucketed alphabetically
If client request comes in for "ove" find all words starting with ove, ordered by popularity
Return top matches to client
There's an excellent open-source Country selector in the Smashing Magazine article (link below) which includes a discussion of the usability challenges with plain autocomplete solutions, and fixes them.
While I'm UX, not Dev, I'm certain a clever developer could adapt this open-source code to handle other kinds of selections—not just the names of countries. :)
The article that describes the usability issues that this selector resolves.
The demo and open-source download. Try it!
Disclaimer: I have no connection to the folks who made this Country selector. I just happen to know about it, and I like to share information about Usability with developers, FWIW.
There's as many answers to this as there are different implementations of them. Our AutoCompleter which you can see a sample of in Stacked works by raising an event which then is handled in the codebehind of the .ASPX page from which you populate a ControlCollection with whatever controls you wish. We're however in Stacked only using Literal controls with Text content being anchor links. But we could add up checkboxes or images if we wanted to...
If you're on ASP.NET our AutoCompleter is a great place to start. If you're on "something else" then probably ScriptAculous AutoCompleter is another nice place to start...
i also have been recently working on autocomplete feature and we used lucene to index the text to be shown in autocomplete. Searching is fast with lucene. Somethings to look at when working with autocomplete data:
Freshness of suggestions,
Dependency on the long term data,
Regional dependency,
Language dependency
Update 2022
The marked answer is a little outdated. Suggestions autocomplete seems like magic on the surface but really what it is under the hood is
fast asynch communication and
searching through a list of keywords
Send a string to your database then return response in JSON to loop/iterate through. Then repeat as user types.
One good example is done with YELP Fusion.
Below is example with small library autocomplete.js
$(function () {
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Haskell",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"
];
$(".sbx-custom__input").autocomplete({
source: availableTags
});
});
<!--jqueryui-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.13.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/ui/1.13.1/jquery-ui.js"></script>
<!--autocompletejs-->
<script src="https://cdn.jsdelivr.net/npm/#tarekraafat/autocomplete.js#10.2.6/dist/autoComplete.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/#tarekraafat/autocomplete.js#10.2.6/dist/css/autoComplete.min.css">
<!--input-->
<input class="sbx-custom__input" autocomplete="on" required="required" placeholder="autocomplete...">
here is the simple example from my code(using jquery + jquery ui). first i requested all data with ajax that i prefixed to inbox then i clicked one of them and so it redirects to another action succesfully.
$("#Name").autocomplete({
source: function (request, response) {
var prefix = { Name: request.term};
$.ajax({
url: '#Url.Action("FilterMastersByName", "JsonResult")',
data: JSON.stringify(prefix),
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data, function (item) {
return item;
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
select: function (e, i) {
var abc=i.item.val;
let a = document.createElement('a');
a.href = `/Home/GetMasterById?masterId=${abc}`;
a.click();
},
minLength: 1
});
});
Dont forget setFilterMastersByName action to httppost and GetMasterById to httpget
Here is one for MooTools.