How to load an external javascript file asynchronously within popup.html? - javascript

I've got everything working, but after adding an external javascript file (which is, by the way, only a couple of short lines in length), it delays loading of the popup.html.
This delay is annoying, and I think by asynchronously loading the javascript file, then it will get rid of this lag.
The file is written in popup.html like this:
<script src="https://domain.com/myexternalscript.js"></script>
I'm not sure how to asynchronously load this file. So how can I do this?

Since you are developing for Chrome, I do understand the problem with inlining a script before load.
I wrote this AJAX(jQuery) snippet, hope you'll find it usefull:
$.ajax({
type: "GET", //or post?
url: "http://FOOBAR.COM", //change the url obviously..
datatype: "script", //identify the expected income
async: "true", //async is "true" by default, but let's make sure it's #t
success: function(result) {
/**now we append the script to the document, nothing too special,
just pay attention we inject it INSIDE the item and not as the src**/
var scr = document.createElement('script');
scr.innerHTML = result;
document.body.appendChild(scr)
},
error: function(result) {
//a simple error handling using the same method we used for the success
console.log(result)
var scr = document.createElement('script');
scr.innerHTML = "alert('ERROR!')";
document.body.appendChild(scr)
}
});

There are two solutions:
Move the script tag to the end of the html page.
Use the defer attribute on the script tag, which, however, is not supported by older browsers.

The delay could be because the source is a secure http (https) request, instead of just a plain-vanilla http request. Depending on your particular hosting plan, this may or may not make a difference. Arguments and evidence have been made and presented to support this notion and the contrary.
I don't think loading the file asynchronously will solve your problem, because you would be making the same http request... which is what AJAX does; It allows us to request information from the server without reloading the page.
If it's just a couple lines of JS, then why not just include it in your .html document?
Also, you haven't described issue that you are encountering very well. Perhaps you can elaborate?

Related

Setting HTML frame src not working in Safari

I am tasked to rewrite Javascript code built from the year 2000 because it only works in an IE browser. It needs to work in all browsers.
Obviously this was well before AJAX and they used framesets (not even iframe yet) to execute remote JSP/servlet calls into an HTML frame. These frames don't display any HTML other than the main frame. Then you need to make sure you update the code references to know which code to execute from which frame. The frames are a headache, but I have gotten these calls to work in all browsers except Safari.
$('frame[name="RegtypeFrame"]', window.parent.document).attr("src", url);
From there, I am going to the top most document to find the specific frame to load. The url variable is a JSP page that has javascript created by Java scriptlets. Nightmare, yes, but I don't have time/approval to re-write from scratch.
I have tried window.top in Safari but no luck. The code does not execute at all in Safari. I have also tried bypassing the frames altogether by using an AJAX GET, which works in all browsers, but since it is javascript I have to use eval which is a valid security risk.
$.ajax(
{
url: url,
method: "GET",
async: true,
dataType: "html"
}).done(
function(html)
{
// major security risk to use eval on remote javascript code
var dom = $(jQuery.trim(html));
dom.filter('script').each(function()
{
$.globalEval(this.text || this.textContent || this.innerHTML || '');
});
}).fail(
function(jqXHR, textStatus)
{
alert("Request failed: " + textStatus);
});
Does anyone have any suggestions or alternatives on how to resolve this issue? I have a workaround but it is a flawed security risk.
The original code seems to be working in Safari now, though I'm not sure of the reason why. I cleared the developer cache on previous attempts. Maybe there are other caches I'm not aware of. If you attempt to select the frame by id, it won't work for a non-iframe.
$('frame[name="RegtypeFrame"]', window.parent.document).attr("src", url);

phantomJS includeJs method always fails to load script via Operation Cancelled

I'm trying to load some scripts into my pages being visited by phantomjs. I'm using 2.1.1 btw.
I'm kind of banging my head here because I've tried a variety of things and they all seem to fail in the same way which kind of makes me think maybe I'm missing a configuration setting or something.
Any who what I'm trying :
//I dont actually care about using jquery, just trying loading from different servers
page.includeJs('http://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js');
and
page.includeJs('https://aSiteIControl.com/jquery.min.js');
and then I have a onResourceError handler like this:
page.onResourceError = function(resourceError) {
console.error(resourceError.url + ': ' + resourceError.errorString);
console.error(JSON.stringify(resourceError))
};
that outputs this no matter what I've tried:
https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js: Operation canceled
{"errorCode":5,"errorString":"Operation canceled","id":1,"status":null,"statusText":null,"url":"https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"}
This seems to happen no matter what protocol I use or what server the script lives on. Also, both of those examples are visitable in a browser. Any body have any idea what I might be doing wrong?
TO BE CLEAR on the accepted answer since there is no code:
just go look at this question :
PhantomJS: injecting a script before any other scripts run
I bet you can include directly only local scripts. Please try:
(page.evaluate(function() {
var script = document.createElement('script');
script.src = 'http://urlToScript.com';
}))
This can be caused by a timeout or the call to the exit() function of the phantom object while the js is being loaded, or if you try to open another page. Can you add all your code?
Based on the documentation you can include external JS:
Includes external script from the specified url (usually a remote location)

IE8 AJAX error: javascript is not loaded

I have a fairly complicated page built using JSP, JavaScript, jQuery, and css. It works fine in Chrome, Firefox, and IE10. However, it doesn't work in IE8 - JavaScript specific to that particular page doesn't load, the HTML is broken, some css is loaded, but not all.
The page called via an AJAX call:
jQuery.ajax({
url : url,
dataType: "html",
cache : false,
beforeSend : ...
Capturing network activity in Developer tools shows that the relevant script files have started to arrive, but only 155B-157B were received. Result code is 304, time is shown as under 1ms.
Same reporting for Chrome shows that the same JS files are 3-7-12KB in size, took 3-10ms to arrive, with HTTP code 200.
The same page requested via a regular GET request loads normally.
The problem looks like a known aggressive-caching issue in IE8, but somehow setting cache : false doesn't prevent 304 from happening.
How can I make this work?
Using jQuery version 1.4.2, IE8 on Win7. tc Developer server 2.8.2.
One of the JavaScript files being retrieved via the AJAX call contained, among other code, this method:
jQuery(document).ready(function() {
return validate...();
}
IE8 was not able to process it, and discarded all surrounding JavaScript.
I removed the lines above, and moved the validation method to the function that was called on Complete: of that AJAX call, and everything started working.

Detect and log when external JavaScript or CSS resources fail to load

I have multiple <head> references to external js and css resources. Mostly, these are for things like third party analytics, etc. From time to time (anecdotally), these resources fail to load, often resulting in browser timeouts. Is it possible to detect and log on the server when external JavaScript or CSS resources fail to load?
I was considering some type of lazy loading mechanism that when, upon failure, a special URL would be called to log this failure. Any suggestions out there?
What I think happens:
The user hits our page and the server side processes successfully and serves the page
On the client side, the HTML header tries to connect to our 3rd party integration partners, usually by a javascript include that starts with "http://www.someothercompany.com...".
The other company cannot handle our load or has shitty up-time, and so the connection fails.
The user sees a generic IE Page Not Found, not one from our server.
So even though my site was up and everything else is running fine, just because this one call out to the third party servers failed, one in the HTML page header, we get a whole failure to launch.
If your app/page is dependent on JS, you can load the content with JS, I know it's confusing. When loading these with JS, you can have callbacks that allow you to only have the functionality of the loaded content and not have to worry about what you didn't load.
var script = document.createElement("script");
script.type = "text/javascript";
script.src = 'http://domain.com/somefile.js';
script.onload = CallBackForAfterFileLoaded;
document.body.appendChild(script);
function CallBackForAfterFileLoaded (e) {
//Do your magic here...
}
I usually have this be a bit more complex by having arrays of JS and files that are dependent on each other, and if they don't load then I have an error state.
I forgot to mention, obviously I am just showing how to create a JS tag, you would have to create your own method for the other types of files you want to load.
Hope maybe that helps, cheers
You can look for the presence of an object in JavaScript, e.g. to see if jQuery is loaded or not...
if (typeof jQuery !== 'function') {
// Was not loaded.
}
jsFiddle.
You could also check for CSS styles missing, for example, if you know a certain CSS file sets the background colour to #000.
if ($('body').css('backgroundColor') !== 'rgb(0, 0, 0)') {
// Was not loaded.
}
jsFiddle.
When these fail, you can make an XHR to the server to log these failings.
What about ServiceWorker? We can use it to intercept all http requests and get response code to log whether the external resource fails to load.
Make a hash of the js name and session cookie and send both js name in plain and the hash. Server side, make the same hash, if both are same log, if not, assume it's abuse.

Problem Fetching JSON Result with jQuery in Firefox and Chrome (IE8 Works)

I'm attempting to parse JSON using jQuery and I'm running into issues. Using the code below, the data keeps coming back null:
<!DOCTYPE html>
<html>
<head>
<title>JSON Test</title>
</head>
<body>
<div id="msg"></div>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$.ajax({
url: 'http://datawarehouse.hrsa.gov/ReleaseTest/HGDWDataWebService/HGDWDataService.aspx?service=HC&zip=20002&radius=10&filter=8357&format=JSON',
type: 'GET',
dataType: 'json',
success: function(data) {
$('#msg').html(data[0].title); // Always null in Firefox/Chrome. Works in IE8.
},
error: function(data) {
alert(data);
}
});
</script>
</body>
</html>
The JSON results look like the following:
{"title":"HEALTHPOINT TYEE CAMPUS","link":"http://www.healthpointchc.org","id":"tag:datawarehouse.hrsa.gov,2010-04-29:/8357","org":"HEALTHPOINT TYEE CAMPUS","address":{"street-address":"4424 S. 188TH St.","locality":"Seatac","region":"Washington","postal-code":"98188-5028"},"tel":"206-444-7746","category":"Service Delivery Site","location":"47.4344818181818 -122.277672727273","update":"2010-04-28T00:00:00-05:00"}
If I replace my URL with the Flickr API URL (http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?), I get back a valid JSON result that I am able to make use of.
I have successfully validated my JSON at JSONLint, so I've run out of ideas as to what I might be doing wrong.
Any thoughts?
Update: I had the client switch the content type to application/json. Unfortunately, I'm still experiencing the exact same problem. I also updated my HTML and included the live URL I've been working with.
Update 2: I just gave this a try in IE8 and it works fine. For some reason, it doesn't work in either Firefox 3.6.3 or Chrome 4.1.249.1064 (45376). I did notice a mistake with the data being returned (the developer is returning a collection of data, even for queries that will always return a single record), but it still baffles me why it doesn't work in other browsers.
It might be important to note that I am working from an HTML file on my local file system. I thought it might be a XSS issue, but that doesn't explain why Flickr works.
Flickr's API supports JSONP, whereas the one you're connecting to does not.
jQuery sees that =? and understands there's a request for a JSONP callback and creates one. You can see it on line 5003 of the jQuery library your sample page uses.
So, you need to change two things
Add a callback parameter to your request. Whatever you (or your developer) wants to call it. Let's say you choose cb - so add this to the AJAX request: &cb=? (this way we let jQuery handle the creation of a callback for us)
Have your developer that made the service accept this new parameter, and "pad" the result with it before returning it.
Have you considered using the more flexible $.ajax? I would break it down there and see if the default $.getJSON is not providing you with exactly what you need.
$.ajax({
url: 'results.json',
type: 'GET',
dataType: 'json',
success: function(data, status)
{
alert(data);
}
});
Would be the equivalent ajax 'parent' implementation. Try mucking around and see if there is a specific property you need to set.
Is the content served as "application/json"?
if one url (the flickr url) works, while another doesnt (your own), i would say the problem is with your url.
It looks like you are using a relative path, is that your intention? have you used firebug's net panel to see what the request looks like?
This is a case of Crossdomain request error. Flickr Works , because it is JSONP , while the other url does not work because it is not JSONP enabled.
1. Check if the url supports JsonP
2. if not, create a proxy web service in your local domain (the same domain as the web page is)
3. Call that proxy webservice which in turn calls the external url from the server side.

Categories