Google Maps asynchronous loading with AWS Cloudfront - ruby-on-rails

My google-map is only loading asynchronously after a page reload or an HTTP redirect. For the first onload, it won't appear-- none of the javascript is called.
In Rails development mode, it works without any problem. Likewise, the map loads asynchronously in production mode if I serve assets locally. But when I configure Amazon Web Services' Cloudfront CDN, it fails on the first page load.
Here's the javascript from the view that calls the map:
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
function initialize() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
streetViewControl: false,
overviewMapControl: false,
mapTypeControl: false,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.DEFAULT,
},
center: new google.maps.LatLng(39.82, -98.58),
});
// Info Window Content
var infoWindowContent = <%= raw #content %>;
var locations = <%= raw #location %>;
// Display multiple markers on a map
var infowindow = new google.maps.InfoWindow(), marker, i;
var marker, i;
var markers = new Array();
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
markers.push(marker);
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(infoWindowContent[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
}
function loadScript() {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp&' +
'callback=initialize';
document.body.appendChild(script);
}
window.onload =loadScript;
</script>
Any idea what may be going wrong with the code on AWS Cloudfront?

Wow. Finally solved this.
A few things went wrong.
First, AWS S3 and Cloudfront do not allow CORS, or Cross Origin Resource Sharing, by default. This means that you cannot call an AJAX resource served by either-- it won't work. That said, you can configure both to allow CORS. To do so, you need to edit your S3 bucket permissions and add a CORS Configuration (AWS offers good examples on help pages). Next, you need to whitelist the 'Origin' header on your Cloudfront distribution. This will allow cloudfront to forward the Origin header from the request to the response, and allow CORS. (I didn't fully get this to work. Check AWS help resources on CORS for more information)
Second, I noticed that even though my AJAX script was served locally and not by Cloudfront, a different javascript file was: my Turbolinks js file. It turns out the Turbolinks gem that the Rails Asset Pipeline requires creates a js file ended up being uploaded to my distribution (it's required by default in the application.js file). If you read the Turbolinks documentation, you'll see that Turbolinks ensures only reloads the html body and title of the head. Here's this from the README:
"Instead of letting the browser recompile the JavaScript and CSS between each page
change, it keeps the current page instance alive and replaces only the body and
the title in the head"
As it turns out, the Turbolinks interfered with the local AJAX and prevented the Google Map from loading asynchronously. Since the AWS CORS configuration evaded me, I simply added the option to turn turbolinks off for the link leading to the Google Map page:
data: { no_turbolink: true }
to make the full link:
<%=link_to "/map", data: { no_turbolink: true } %>
With no turbolinks, the page was never called using the Cloudfront Turbolinks.js file, and thus the local AJax could load the Google Map.
I hope this helps ye weary travelers!

Related

Rails 5: Google Tag Manager will not fire

I am using Google Tag Manager and it just stopped working on the landing page that client's are redirected to after filling out a form. It works if you refresh the page, but doesn't work on redirects.
I know this smells like turbolinks, so I've modified the javascript function like so many articles have recommended:
<script>
document.addEventListener('turbolinks:load', function(event) {
console.log(event, dataLayer)
var url = event.data.url;
dataLayer.push({
'event':'pageView',
'virtualUrl': url
});
});
(function(w,d,s,l,i){
console.log("getting it")
w[l]=w[l]||[];w[l].push({
'gtm.start': new Date().getTime(),event:'gtm.js'
});
var f=d.getElementsByTagName(s)[0],j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src='https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})
(window,document,'script','dataLayer','GTM-######');
</script>
In my console, I see the console.log(event, dataLayer) but there is no request to: https://www.googletagmanager.com/gtm.js?id=GTM-######
When I refresh the page, I see the same things logged to my console, but there IS a request to https://www.googletagmanager.com/gtm.js?id=GTM-######.
Does anyone know how to make this request fire or understand what might be going wrong?

YouTube API Academy

I just completed the YouTube API tutorials on Codecademy and successfully managed to display results relating to a given 'q' value in the console window provided using the following code:
// Helper function to display JavaScript value on HTML page.
function showResponse(response) {
var responseString = JSON.stringify(response, '', 2);
document.getElementById('response').innerHTML += responseString;
}
// Called automatically when JavaScript client library is loaded.
function onClientLoad() {
gapi.client.load('youtube', 'v3', onYouTubeApiLoad);
}
// Called automatically when YouTube API interface is loaded (see line 9).
function onYouTubeApiLoad() {
// This API key is intended for use only in this lesson.
// See http://goo.gl/PdPA1 to get a key for your own applications.
gapi.client.setApiKey('AIzaSyCR5In4DZaTP6IEZQ0r1JceuvluJRzQNLE');
search();
}
function search() {
// Use the JavaScript client library to create a search.list() API call.
var request = gapi.client.youtube.search.list({
part: 'snippet',
q: "Hello",
});
// Send the request to the API server,
// and invoke onSearchRepsonse() with the response.
request.execute(onSearchResponse);
}
// Called automatically with the response of the YouTube API request.
function onSearchResponse(response) {
showResponse(response);
}
and:
<!DOCTYPE html>
<html>
<head>
<script src="search.js" type="text/javascript"></script>
<script src="https://apis.google.com/js/client.js?onload=onClientLoad" type="text/javascript"></script>
</head>
<body>
<pre id="response"></pre>
</body>
</html>
The problem I am having now is that I have taken this code and put it into my own local files with the intention of furthering my understanding and manipulating it work in a way which suits me, however it just returns a blank page. I assume that it works on Codecademy because they use a particular environment and the code used perhaps only works within that environment, I am surprised they wouldn't provide information on what changes would be required to use this outside of their given environment and was hoping someone could shed some light on this? Perhaps I am altogether wrong, if so, any insight would be appreciated.
Browser Console Output:
Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('file://') does not match the recipient window's origin ('null').
I also had the same problem but it was resolved when I used Xampp. What you have to do is install xampp on your machine and then locate its directory. After You will find a folder named "htdocs". Just move your folder containing both js and HTML file into this folder. Now you have to open Xampp Control Panel and click on start button for both - Apache and SQL server. Now open your browser and type in the URL:
http://localhost/"(Your htdocs directory name containing both of your pages)"
After this, click on .html file and you are done.

InAppBrowser inject script (using executeScript)

InAppBrowser js scripts injection using {code: 'some code'} param is working perfectly but not with {file: 'local file url'} param.
var ref = window.open('http://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstop', function() {
ref.executeSript({file: "myscript.js"});
});
how do I go about injecting script using the file param to inject my local js script?
does it require absolute file path or relative?
Must file be hosted on the child website?
It seem like a mysterious complicated thing to do as I have a few lines of script and can't embed it all using ref.executeSript({codedetails, callback: "myscript.js"});
I had the same problem. Using cordova3.1.0.
ref.executeScript(
{
file: "http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"
//webURL works fine with 'file'
}, function()
{ 
$.get("js/myscript.js", function(data)
{ //workaround to obtain code using jQuery.get
ref.executeScript(
{
code: data
}, function()
{ 
console.log('ref.executeScript done');
});
});
});
When I set the file URL as webURL http://.... ,
it worked, but I could not figure out how to point the local js file,
so I obtain code strings using $.get "js/myscript.js".
The sample code illustrates: jQuery is already installed on the phonegap App, and also trying to use jQuery on the target inAppBrowser app. Just in case.

Broken relative Url in jQuery getJSON Ajax Method

The Url for my development environment is:
http://localhost/mysite/blah...
I am using jQuery & getJSON to perform some ajax actions on my site, which work fine all the time I specify the url as:
/mysite/controller/action
..but this is not ideal as I don't want to hardcode my development url into my seperate jQuery include files.
When the site goes live, it'll be fine to have controller/action or /controller/action as the url as that will resolve ok, but for the development site, it's no go.
I've tried:
controller/action
..but this returns a 404, which suprised me as I thought the lack of / at the front of the url would prevent from looking at the website root.
There must be a neat solution to this?
I would do this by inserting a global constant in my HTML header:
<script type="text/javascript">
var BASE_URL = '/mysite/';
</script>
That would be inserted from your server so it can be dynamically changed.
Later in your script, you'll be able to make AJAX requests with (jQuery style here):
$.ajax( BASE_URL + '/controller/action', ...);
If you're in
/mysite/controller/action
then the correct relative path to
/mysite/some_other_controller/some_other_action
is
../../some_other_controller/some_other/action
You can use this code to get the current path of the .js script and use it for calculate your relative path.
var url;
$("script").each(function () {
if ($(this).attr("src").indexOf("[YOUR_SCRIPT_NAME.JS]") > 0) {
url = $(this).attr("src");
url = url.substr(0, url.lastIndexOf("/"));
return false;
}
});
var final_url = url + "/your_target_script.js"
Replace YOUR_SCRIPT_NAME with the unique name of your script.

HTML5 App Cache not working with POST requests

I'm working on a web application and I went through the necessary steps to enable HTML5 App Cache for my initial login page. My goal is to cache all the images, css and js to improve the performance while online browsing, i'm not planning on offline browsing.
My initial page consist of a login form with only one input tag for entering the username and a submit button to process the information as a POST request. The submitted information is validated on the server and if there's a problem, the initial page is shown again (which is the scenario I'm currently testing)
I'm using the browser's developers tools for debugging and everything works fine for the initial request (GET request by typing the URL in the browser); the resources listed on the manifest file are properly cached, but when the same page is shown again as a result of a POST request I notice that all the elements (images, css, js) that were previously cached are being fetched form the server again.
Does this mean that HTML5 App Cache only works for GET requests?
Per http://www.whatwg.org/specs/web-apps/current-work/multipage/offline.html#the-application-cache-selection-algorithm it appears to me that only GET is allowed.
In modern browsers (which support offline HTML), GET requests can probably be made long enough to supply the necessary data to get back data you need, and POST requests are not supposed to be used for requests which are idempotent (non-changing). So, the application should probably be architected to allow GET requests if it is the kind of data which is useful offline and to inform the user that they will need to login in order to get the content sent to them for full offline use (and you could use offline events to inform them that they haven't yet gone through the necessary process).
I'm having exactly the same problem and I wrote a wrapper for POST ajax calls. The idea is when you try to POST it will first make a GET request to a simple ping.php and only if that is successful will it then request the POST.
Here is how it looks in a Backbone view:
var BaseView = Backbone.View.extend({
ajax: function(options){
var that = this,
originalPost = null;
// defaults
options.type = options.type || 'POST';
options.dataType = options.dataType || 'json';
if(!options.forcePost && options.type.toUpperCase()==='POST'){
originalPost = {
url: options.url,
data: options.data
};
options.type = 'GET';
options.url = 'ping.php';
options.data = null;
}
// wrap success
var success = options.success;
options.success = function(resp){
if(resp && resp._noNetwork){
if(options.offline){
options.offline();
}else{
alert('No network connection');
}
return;
}
if(originalPost){
options.url = originalPost.url;
options.data = originalPost.data;
options.type = 'POST';
options.success = success;
options.forcePost = true;
that.ajax(options);
}else{
if(success){
success(resp);
}
}
};
$.ajax(options);
}
});
var MyView = BaseView.extend({
myMethod: function(){
this.ajax({
url: 'register.php',
type: 'POST',
data: {
'username': 'sample',
'email': 'sample#sample.com'
},
success: function(){
alert('You registered :)')
},
offline: function(){
alert('Sorry, you can not register while offline :(');
}
});
}
});
Have something like this in your manifest:
NETWORK:
*
FALLBACK:
ping.php no-network.json
register.php no-network.json
The file ping.php is as simple as:
<?php die('{}') ?>
And no-network.json looks like this:
{"_noNetwork":true}
And there you go, before any POST it will first try a GET ping.php and call offline() if you are offline.
Hope this helps ;)

Resources