Unload Google Maps API? - ajax

I have a main page that uses ajax to load subpages and one of these subpages contains a google map, and so it loads the google maps api using the <script> tag:
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&sensor=SET_TO_TRUE_OR_FALSE">
I noticed that this loads a bunch of css and js files into both my main page and subpage. When I click on a different link in my main page, I want to be able to unload all of these files and remove any js objects that were created, i.e., clean up everything and return to the original state. Is there any way to do this?

The answer to your question is actually a bit more complicated than you might think. A good question and set of answers that deal with many of the related details are at: What is the Proper Way to Destroy a Map Instance?.
I'm not sure from your question, but it sounds like you may have created a page that loads the Google Maps API more than one time (or could, depending on user choices) and you should avoid that entirely. Google admits there are memory leak bugs associated with reloading the map and strongly recommends against multiple map reloads. Google essentially does not support multiple map load use cases.
Check out some of the information available at the question link included above; it contains some good discussion and information.
EDIT in Response to #Engineer's Comment:
Check out the Google Maps API Office Hours May 9 2012 Video where Chris Broadfoot and Luke Mahe from Google discuss: that they don't support use cases that involve reloading the map, that the API is intended to be loaded only once, and their acknowledgement that there is a memory leak bug. Set the playback to ~12:50 to view the section about destroying the map, problems with reloading the map, and suggestions they offer to avoid problems. Primarily, if you must hide and then show a map, they recommend reusing a single map instance.

Old question.. But here is my solution:
// First getting rid of the google.maps object (to avoid memory leaks)
// Then, we are also removing google-maps related script tags we can identify.
// After unloaded, if maps is reloaded more than once on the same page;
// we'll also get a warning in the console saying: "Warning: you have included the
// Google Maps API multiple times on this page. This may cause unexpected errors."
// This script will also avoid that warning.
if (window.google !== undefined && google.maps !== undefined) {
delete google.maps;
$('script').each(function () {
if (this.src.indexOf('googleapis.com/maps') >= 0
|| this.src.indexOf('maps.gstatic.com') >= 0
|| this.src.indexOf('earthbuilder.googleapis.com') >= 0) {
// console.log('removed', this.src);
$(this).remove();
}
});
}
Update: Note that this is not a full-proof solution. There might be copied/cloned/referenced objects. A better way would be to sandbox the map in an iframe and remove the iframe from DOM.

Not the way you're thinking. The easiest way to accomplish this would be to use an iframe to load the "heavy" parts of your application. Then when you get rid of the iframe you get rid of the CSS and JS associated with the map.
In version 2 the Google Maps API had a GUnload() call but the version 3 API doesn't have this call.

with vanilla JavaScript:
if (window.google?.maps) {
delete google.maps
document.querySelectorAll("script").forEach((script) => {
if (
script.src.includes("googleapis.com/maps") ||
script.src.includes("maps.gstatic.com") ||
script.src.includes("earthbuilder.googleapis.com")
) {
script.remove()
}
})
}

Related

How do I hide posts with a specific hashtag in Yammer?

I want to hide posts in the feed that have a #joined hashtag. I tried to create a GreaseMonkey script with jQuery in the past, but it couldn't detect any posts that have the #joined text.
Am I using the wrong library? A starting point, or an existing library/plug-in would be helpful.
OFF-TOPIC: At the moment, Yammer does not have any feature to hide posts with a specific hashtag, although it has a feature to follow a hashtag.
I know that this is a pretty old question but I too was trying to create a Chrome based Add-on that hides these #joined posts (or any post with a specific hashtag). I came across this blog https://you.stonybrook.edu/thebaron/2014/10/06/hiding-joined-yammer-posts-in-chrome/ where the author of the post has shared his work (https://gist.github.com/thicknrich/e4cc2871462a6850fe8c). This is a simple javascript and does the job.
//Script from https://gist.github.com/thicknrich/e4cc2871462a6850fe8c
//load jQuery based on this SO Post:
//http://stackoverflow.com/questions/2246901/how-can-i-use-jquery-in-greasemonkey-scripts-in-google-chrome
// a function that loads jQuery and calls a callback function when jQuery has finished loading
function addJQuery(callback) {
var script = document.createElement("script");
script.setAttribute("src", "//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js");
script.addEventListener('load', function() {
var script = document.createElement("script");
script.textContent = "window.jQ=jQuery.noConflict(true);(" + callback.toString() + ")();";
document.body.appendChild(script);
}, false);
document.body.appendChild(script);
}
// the guts of this userscript
function main() {
// Note, jQ replaces $ to avoid conflicts.
setInterval(function() {
//if a item thread contains #joined, hide it
//check every 5 second.
jQ('.yj-thread-list-item:contains("#joined")').css("display", "none");
}, 5000);
}
// load jQuery and execute the main function
addJQuery(main);
You can find all joined messages with the following endpoint, based upon the #joined topic:
GET https://www.yammer.com/api/v1/messages/about_topic/[:id].json
But you can only delete messsages that you own:
DELETE https://www.yammer.com/api/v1/messages/[:id]
Source: https://developer.yammer.com/restapi/
Note that this is a conscious decision by the product team, although joined messages can get spammy when a network becomes viral, it is a great opportunity to engage users right away once they join. It makes them feel welcome. As a community manager, I'd encourage you to welcome that user in and also encourage other yammer champions to welcome these users also. As a side effect, it also encourages people to follow the groups they are interested in and use the Top or Following feeds instead of the all (firehose) feed which has all these joined messages.
Just want to note that the statement in a reply here "But you can only delete messsages that you own" is not entirely correct it is possible to delete message that do not belong to you if you are a network admin. I just ran a little experiment after reading this post and deleting #joined messages that don't belong to me worked just fine.

How to make wp plugin auto-refreshing on the public side of view (auto load page)

First have to say that almost every time when searching on technical solutions.. search engine will direct me to this site here. I admit that i have learned such A LOT here just by searching through for answers..
but also have to say that not being a coder.. so don't understand much here at all ;)
Ok, the Problem:
Want to update wordpress tables or calendar within wp admin. These changes should become updated on the public side automatically and more or less instantly (~ few seconds is perfectly fine).
I found solutions about manipulating header.php, i found some ajax plugins I found -too much to count- info on how to implement ajax into wp
Sadly.. none of these could help me through as the plugins mostly either not work, are outdated or require countless file edits. Manipulating header.php seems odd.. as i don't want to loop-refresh the whole page, post etc.. but only get e.g. table or calendar data updated.
So maybe any of you coders know of something to e.g. get the plugin "All-in-One Event Calendar by Timely" to update the public visible part of the calendar once data edited in wp admin?
Greatly appreciate pointers in any direction to solve this.
P.S.: What would you think of plugins like "ajaxify everything" ? don't know if this really the way to go..
Again, thanks for your help, time and contribution!!
update
additional question:
I now found such plugin to let me chose which parts i want to "ajaxify".
Such plugin would ask me for a specific function name.
Now, where do i start to gather this information?
Below is the instruction from the plugin context inside wordpress admin
Generate Ajaxized DIV for your function
Ajaxize will allow you to ajaxize almost any php function on your
site.
It can be a plugin, a function you wrote, or even a core wordpress
function.
There are some (obvious or less obvious) limitations currently:
Functions must return valid HTML - this will be called in php and returned via the
Ajax call
Functions cannot accept any parameters (at least at the moment)
Enter a function name below.
Function Name: xxx input field xxx what put in here? xxx
The generated div can be inserted to any page/post on the site and
will ajaxize the call to the function automatically.
Please make sure you enter a valid function name, that the function
does not require any parameters, and that it returns valid HTML.
In your context you want to refresh the calendar automaticaly when there is a change in the WP_Admin;
but you can't exactly do this.
You can write a Js method which will check the time of lastest modification of the calendar at the load of the page, stock it in Var.
After you'll have a constant (each 10seconds) Js "daemon" which will get the time of lastest modification of the calendar and compare it to the stocked Var; If change you reload the calendar.
PS: Ajaxify everything is not really a solution due of the developpement you need To Ajaxify and to code for people who has disabled Javascript.
Hope it helps

django update page when database field updates?

I have a results page and I am trying to work out how to auto update the page when an external database field is updated. I have seen quite a few examples but they seem to relate to PHP. I have a test that calls various APIs that can take up to an hour to complete. Once the test has completed, it will enter a success or failed message in a database field.
I already have my results page being rendered by django using template tags. I have a table and I have the field I would like to update. There are multiple fields that need update which correspond to each API test.
I have seen this site.. is this the kind of stuff to use? http://www.dajaxproject.com/ Is this an easy task to do? Does anyone have any ideas on how to do this?
Sorry but I don't know where to start on this one.
Cheers - Oli
I decided not to be so bold and just use the old classic page update for this purpose using javascript..
window.onload = setupRefresh;
function setupRefresh() {
setTimeout("refreshPage();", 30000); // milliseconds
}
function refreshPage() {
window.location = location.href;
}
Still open for options however I'm rather inexperienced in django and maybe this was too much to bite off too quickly..

Adobe AIR HTML - How do I dynamically load an image located in app-storage?

I'm working on an AIR application which generates a dynamic client presentation, pulling all necessary data from a PHP framework API. In the process, I download a large number of images and store them locally in the user's app-storage (air.File.applicationStorageDirectory).
Side note: the HTML view I am dynamically populating is located in an IFRAME sandbox.
I have a parsing script which attempts to take JSON data and populate the page with the necessary fields. Many of these fields are images that I need to locally reference. I thought I might be able to simply generate the URL using <img src="app-storage:/path/to/img.jpg"> but it doesn't seem to actually load the image. My guess is AIR doesn't handle app-storage: url references dynamically. Is there a work-around for this? Could I perhaps use jQuery and load()?
Here is the current code I am using which is not working:
var pos = filename.lastIndexOf(".");
if (pos != -1) {
ext = filename.substr(pos + 1, filename.length);
switch (ext) {
case 'gif':
case 'jpg':
case 'jpeg':
case 'png':
default:
// update the source value
$field.attr('src', 'app-storage:' + filename);
break;
}
}
I thought I might be on the right track because the return result of
air.File.applicationStorageDirectory('test')
was app-storage:/test
Any help would be greatly appreciated!
The solution ended up being that I had to properly set the IFRAME to have Application security level access, granting it privileges to use handle app-storage urls properly. For those interested in knowing how you can go about doing this, the first step is to simply have the IFRAME file you wish to load directly in the application's main directory:
<iframe id="childFrame" src="child.html" documentRoot="app:/" allowcrossDomainxhr="true" width="100%" height="100%"></iframe>
The key difference in this sandbox is that it doesn't have the parameter sandboxRoot.
It's worth noting that I never once experienced any security errors during any of my testing. It seemed as though the app-storage URL was just not properly being handled by AIR itself.
people talking than you need to allow security policy there.

Browser history for Flash (or AJAX)

What is the best tool / practice to enable browser history for Flash (or AJAX) websites?
I guess the established practice is to set and read a hash-addition to the URL like
http://example.com/#id=1
I am aware of the Flex History Manager, but was wondering if there are any good alternatives to consider. Would also be interested in a general AJAX solution or best practice.
SWFAddress has been widely used and tested. It makes it almost trivial (given you plan ahead) to handle deeplinking in Flash. It provides a JS and AS library that work together and make the whole process pretty foolproof. You'd want to look at something like RSH for AJAX.
I've used swfadress for some small stuff.
For AJAX, something like Really Simple History is great.
This will seem a bit roundabout, but I'm currently using the dojo framework for that. There's a dojo.back that was very useful when my UI was mostly JS/HTML. Now that I've gone to flex for more power, fluid animations, and browser stability, the only thing I've need to keep using has been the back URL.
FlexBuilder seemed to have it's own browser history in default projects.
Also, the Flex 3 Cookbook has a recipe for using mx.managers.HistoryManager to create your own custom history management. I have plans to give this a try someday to remove our dependence on the dojo.back, but haven't had time yet.
I've rolled my own solutions that were ultra-simple like this:
(function() {
var oldHash, newHash;
function checkHash() {
// Grab the hash
newHash = document.location.hash;
// Check to see if it changed
if (oldHash != newHash) {
// Trigger a custom event if it changed,
// passing the old and new values as
// metadata on the event.
$(document).trigger('hash.changed', {
old: oldHash,
new: newHash
});
// Update the oldHash for the next check
oldHash = newHash;
}
}
// Poll the hash every 10 milliseconds.
// You might need to alter this time based
// on performance
window.setInterval(checkHash, 10);
})(jQuery);
Then you just need to have event handlers for the 'hash.changed' event to respond accordingly based on what the new value is. The approach works will in super simple cases.

Resources