Dynamically load JavaScript with JavaScript - javascript

After over an hour of trying to get it to work I'm thinking it's because of cross domain policies, but I really thought this would work. I can't find a lot of info on it either. But, here is my issue. I have a site called http://mysite.com and then I include a 3rd party script (what im writing) and its at http://supercoolsite.com/api/script.js and this script needs to dynamically load the google maps api at: http://maps.google.com/maps/api/js?sensor=false before it runs. Well, i figured this code would work:
function loadScript(filename,callback){
var fileref=document.createElement('script');
fileref.setAttribute("type","text/javascript");
fileref.setAttribute("src", filename);
fileref.onload = callback();
if (typeof fileref!="undefined"){
document.getElementsByTagName("head")[0].appendChild(fileref)
}
}
loadScript('http://maps.google.com/maps/api/js?sensor=false',function(){
console.log('done loading');
init();
});
But my response in my console is:
api.js:408 done loading
api.js:115 test
api.js:310 Uncaught ReferenceError: google is not defined
the "test" is at the top of the init(). So, it's loading the script, but it's not executing it, it seems. So, any ideas? If it is a cross site scripting issue my only method of fixing this i could think of is having a PHP script on our end that basically just sets the header to a text/javascript header and then echo file_get_contents() into a googlemaps.php file we host. About to try this as we speak, but, if possible, a way to do it with pure JS would be awesome.
P.S. I also tried adding jQuery, then doing getScript(), and it still didnt work
-- UPDATE --
See this fiddle:
http://jsfiddle.net/ycMCa/2/
You'll see that you get the error in your console:
Uncaught TypeError: undefined is not a function
Despite that the google variable is global.

You just have a minor error:
fileref.onload = callback();
This will call callback immediately and assign its return value to fileref.onload.
It should be
fileref.onload = callback;
You also should add the handler before you set the source (just in case).
DEMO

Related

Using startTrackPage in Application Insights

I have recently been messing around with Application Insights and have been having a problem with getting the JavaScript API to work. In the default script that you are supposed to add to your page, they use the function trackPageView(). This seems to works, but I had also wanted to gather information about how long a user stayed on the page. I found the startTrackPage() and stopTrackPage() functions and tried to use those to get the information, but I always receive an error from startTrackPage().
Uncaught TypeError: appInsights.startTrackPage is not a function(anonymous function)
I have stepped through the code and the function does not seem to be created at the point I am calling it. trackPageView() is already defined though. I tried calling the function after the document loaded as well and that still failed. However, I can call it from the developer console once the page loads.
Here is where I found the information about startTrackPage() and stopTrackPage() originally. Other than that I have just been perusing around to see if anyone else has encountered this.
I appreciate the help.
Default code from App Insight:
window.appInsights = appInsights;
appInsights.startPageView();
What I have tried:
window.appInsights = appInsights;
appInsights.startTrackPage();
window.onunload = function () {
appInsights.stopTrackPage();
};
Short answer: unfortunately there's currently no way to use appInsights.startTrackPage() in the way you intend reliably.
Long answer: The reason is that startTrackPage() method is only defined in the JS that is downloaded from CDN, so until it is downloaded it is not defined.
What you could do it something like:
appInsights.queue.push(function(){appInsights.startTrackPage();})
however this would not produce correct measurement, because tracking won't start right away.
So your best approach would be record start time manually, however even that you cannot do reliably. First of all you absolutely don't want to use onunload event as at this point it will be too late for Application Insights SDK to send the data so it will most likely get lost. Using onbeforeunload and flush() will help with this problem a little bit:
var pageStart = +new Date;
window.addEventListener("beforeunload", function () {
appInsights.trackMetric("timeOnPage", (+new Date)-pageStart);
appInsights.flush();
});
However even when using onbeforeunload you are looking at high number of potential data losses - you cannot guarantee that ajax request to send data to Application Insights will complete before page navigates away and connection is interrupted. In my testing with IE was getting about 50% of losses.

JSON-P request to URL does not work?

I've been trying to get this to work for about three hours now. Searched around, looked all over actually, and I tried all the examples people showed, none of which worked. This is really starting to bug me. What I'm trying to accomplish is a call to BitCoin Charts JSON file that holds all the bitcoin data. I am setting up a webstore, and would like the price to be accurate when the user loads the page.
Here is the snippet of code where I call the $.getJSON() function:
function JSONCall() {
var url = "http://api.bitcoincharts.com/v1/weighted_prices.json";
$.getJSON(url + "?callback=?", Update);
}
function Update(data) {
//there will be code here to change the HTML on my site, but for now, this works to test
console.log(data);
}
The current error that I'm experiencing is:
Resource interpreted as Script but transferred with MIME type text/html: "http://api.bitcoincharts.com/v1/weighted_prices.json?callback=jQuery19100276493770070374_1387411109377&_=1387411109490". jquery-1.9.1.js:8336
Uncaught SyntaxError: Unexpected token :
and I cannot for the life of me get it to work. My code looks fine, according to everything I've seen this far. If anybody knows more about this than me and would be willing to help, that would be fantastic! Thanks in advance.
I checked the URL and it doesn’t return JSONP, only plain JSON.
You will need to find another way, some options come to mind:
Do a CORS request (cross-origin) if the service supports it
Run via a server-side proxy
See if the service supports JSONP in some other way

Delete file in Google Drive with Javascript

I'm trying to delete a file using the GDriva API for JavaScript. This page is quit straight forward it seems, but it doesn't work.
https://developers.google.com/drive/v2/reference/files/delete
Looks like it should be easy to do
function deleteFile(fileId) {
var request = gapi.client.drive.files.delete({
'fileId': fileId
});
request.execute(function(resp) { });
}
But I get "Uncaught TypeError: Cannot read property 'files' of undefined"
Does anyone know what's wrong? I have all permissions right. I can create and update a file but not remove it.
UPDATE!
Found this: Deleting a Google Drive file using JS client. There's seems to be a bug in the API. There's a solution which delete the document so that you can't find it with the API, using list, but the document will remain in your Google Drive and will be corrupted. You can view it but not remove or open it.
Sounds like you didn't load the drive client library. Your error message says that gapi.client.drive is undefined. You should have a line like:
gapi.client.load('drive', 'v2', function() { /* Loaded */ });
which will load the drive API and define gapi.client.drive. Make sure you either call delete in the callback, or otherwise ensure that drive is loaded before trying to delete a file.
Or, as #MasNotsram mentioned, you could just use the gapi.client.request syntax for calling delete.

JSONP and DOCTYPE Errors

I'm running into a weird problem.
I'm communicating with my server using AJAX. (I'm running my web application on localhost).
Server is located on, say, http://www.example.com
To bypass the Same Origin Policy, I'm using JSONP. I dynamically create a <script> tag and load the data from my server.
So far so good.
Then I decided to upload my web application to this subdomain: http://m.example.com
That's when I run into crazy errors. Sometimes the page loads, sometimes it doesn't. When it doesn't load, Firebug throws a DOCTYPE error.
I did some research and came across this stackoverflow post: firebug returns syntax error in doctype?
Quoting an answer in this link:
This usually happens because you are loading an HTML document as a script. This is often caused by <script src=""></script> (i.e. a relative URI pointing at the current, HTML, document)) or one of the scripts pointing to a 404 error.
Pretty helpful stuff. Based on all that, I've concluded from all the above that whenever my server responds slowly, the <script> tag's src attribute is null. Since that throws a 404 error, I get a DOCTYPE error in Firebug. Whenever my server responds quickly, there are no issues and everything works fine.
How do I solve this problem? I could put a manual timeout or something, but that wouldn't exactly be foolproof and an elegant solution.
Any help guys?
EDIT:
Here's some code:
This function is used to create the script tag dynamically:
function appendScriptToHead() {
var element = document.createElement("script");
element.src = 'http://www.example.com/?data&callback=callfunction';
document.getElementsByTagName("head")[0].appendChild(element)
}
This callback function is called when the above url containing JSONP data is loaded:
function callfunction(response) {
alert(response);
}
I think there's a bit of misunderstanding here. Your script element will always have its src property set, but its contents depends on your server's response. I doubt it'll be error 404 (as it refers to the element not found, which is hardly repetitive), but it can be of 500 flavors.
I suggest debugging your queries just as they are (i.e., opening http://www.example.com/?data&callback=%callfunction% with your browser or some scripted HTTP UserAgent, if you feel industrious), to see what might be wrong with the logic which selects the script to be loaded.

Debugging javascript code that comes as part of Ajax Response

So in my website, I use jquery to fetch data through ajax. AS part of the ajax response, some of the javascript code comes as well which is executed. The problem is how to debug this javascript in firebug or other tools. This is my experience so far:
putting debugger; doesn't work
For some javascript, can't set the breakpoint as that script is not yet loaded.
even if this new javascript calls some other function thats already loaded (i.e. i can see it in firebug and set a breakpoint), that breakpoint on that function is still not triggered
However, the javascript does executes normally and even things like console.log works but cant seem to debug it..
If you use Google Chrome, check out the answer of this question:
https://stackoverflow.com/a/10929430/482916
You need to add in the ajax-loaded JS scripts the following comment:
//# sourceURL=dynamicScript.js
where dynamicScript.js is the name of the script which will come up in the console.
I know Firebug and the IE developer tools will respect the debugger statement. So I would throw that onto the top of the response.
debugger;
func1();
func2();

Categories

Resources