detect and suppress errors loading javascript file - javascript

I want to source a javascript file from facebook http://connect.facebook.net/en_US/all.js
The organization I work for has a firewall that blocks access to Facebook, it just goes to an html page that says "Access Denied blah blah blah"
I want to be able to put a javascript src tag <script src="http://... "> </script> and detect and suppress the warnings when the browser tries to evaluate the html as javascript.
Anyone know how?

Looks like jQuery.getScript is what you need as was mentioned. Or you can manually execute:
$.ajax({
url: url,
dataType: 'script',
success: function(){document.write('<script src="http://... "> </script>');}
});
And append your html on successful load with the <script></script> tag.

With the standard <script> tag, not possible. There's nothing really running at the time when the script's src is hit and content downloaded, so you can't wrap that in a try/catch block. There's some tips here on how to dynamically load scripts. Maybe the browsers will add some stuff to the DOM element created there which you can check for.

This is a workaround, not a direct answer, but you could simply set up a reverse proxy outside the firewall for Facebook and load the script from there. Instead of failing more gracefully, it would allow the script not to fail.

Try this, and see if it works for you:
<script type="text/javascript" onerror="throw('An error occurred')" src="http://connect.facebook.net/en_US/all.js"></script>
Alternatively, if you have access to a proxy script to grab external content I would use it via an xmlHttpRequest to grab the JS content. If it is successful, eval the content (yes, eval is evil, I know).
I would add that if you know the JS will fail, then why bother?

Why do you not do this in very simple way?:
if(!window.FB) { // or (typeof window.FB === "undefined")
alert ("ERROR: http://connect.facebook.net/en_US/all.js is not loaded");
}
if(!window.jQuery) { // or (typeof window.jQuery === "undefined")
alert ("ERROR: jQuery is not loaded");
}
// and so on

Please try the function below, it will only call the onload_function if the script has loaded. You can set a timeout to cancel the script.
function include_js(url, onload_function) {
var script = document.createElement("script");
script.type = "text/javascript";
if (script.readyState) {
script.onreadystatechange = function(){
if (script.readyState == "loaded" || script.readyState == "complete"){
script.onreadystatechange = null;
onload_function();
}
};
} else {
script.onload = function(){
onload_function();
};
}
script.src = url;
document.getElementsByTagName("head")[0].appendChild(script);
}

In Firefox and IE, you should be able to use window.onerror for this. You can take advantage of the fact that scripts run in the order they are listed in the HTML to wrap an error handler around just the facebook script:
<script>
// Remember old error handler, if there is one.
var oldOnError = window.onerror;
// Special error handler for facebook script
window.onerror = function(message, url, linenumber) {
// Potentially alert the user to problem
alert('Problem with facebook: ...');
// Return true to suppress default error handling
return true;
}
</script>
<!-- Load facebook script -->
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
// Remove error handler for facebook script
window.onerror = oldOnError;
</script>

Related

Load jQuery Only If Not Present without document.write

is there any way to load jQuery file if it's not present without using document.write
<script>
window.jQuery || document.write('<script src="/path/to/your/jquery"><\/script>');
</script>
this way is good but it has major issue because if the visitor has slow connection the browser will prevent it from executing
when it happen I get this warning
file is invoked via document.write. The network request for this script MAY
be blocked by the browser in this or a future page load due to poor
network connectivity
I tried many solutions but nothing worked
You can pass a load callback to the IFFE that will be executed when the script loads or invoked immediately if jQuery exists.
var load = function(){
// your jQuery code goes here
$('#hello').html('jQuery Loaded');
};
(function(window, loadCallback){
if(!window.jQuery){
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "https://code.jquery.com/jquery-3.3.1.min.js";
script.onload = loadCallback;
document.head.appendChild(script);
}else{
loadCallback();
}
})(window, load);
<div id="hello"></div>

async onload not working in this case

I have some code to asynchronously load an Ad on my site which looks like this:
<div id="ad-div"></div>
<script>function onAdReady() {
debug_log('Method onAdReady called');
new Ad(document.getElementById("ad-div"))
}
</script>
<script src="http://content.xxxxx.com/ads/ads.min.js" async onload="onAdReady()"></script>
The problem is that the onAdReady function is never beeing called. The reason for this might be that the html code which contains this snippet is beeing loaded via javascript in the first place like this:
// Initiate out_window_view
$.ajax({
url: loadPagePath("main.html"),
success: function (result) {
debug_log("Going in main.html view");
$("#content").html(result);
},
error: function (result) {
debug_log("Error, failed to load out_window_main view");
}
});
This code is beeing executed in the $(document).ready(function () {] in case that might matter.
Can anyone expalain to me why this is not working and provide me with a workaround or alternative way for solving this issue?
I don't understand why you need to add async to an ajax-generated-content. The purpose of async script is to allow the browser to keep on parsing the document without waiting for the script to fully load. The onload event is called immediately after the script has finished loading and before DOMReady. In other words, async's onload will not fire after DOMReady.
When you add the snippet to your page, the page has already finished parsing, so the async onload event won't fire.
The solution IMO is to remove the async part and just call the function after the <script> synchronously.
You want to load an ad when the page is loaded?
What do you see in the network tab from the debug tools (firebug or F12 in chrome/Firefox)?
Where do you call $( document ).ready() ?
https://learn.jquery.com/using-jquery-core/document-ready/
Can you tell me when you want to send the HTTP request?
If you are able to add the script programmatically, it will be async by default (reference here), and you can listen to the onload or onreadystatechange event (as you can read here, IE11 doesn't support onreadystatechange). Here is an example:
var setup = function(){
console.log('the script has been parsed');
};
var script = document.createElement("script");
script.src = "http://content.xxxxx.com/ads/ads.min.js";
document.getElementsByTagName("head")[0].appendChild(script);
// standard browser
script.onreadystatechange = function (){
if (this.readyState == 'complete'){
setup();
}
}
// IE
script.onload = setup;

how to know if the javascript, which has been loaded by a javascript, has been loaded [duplicate]

This question already has answers here:
'onload' handler for 'script' tag in internet explorer
(2 answers)
Closed 7 years ago.
I know my subject is quite tricky but i dont know how to much more ellaborate it on the subject alone.
so here how it goes.
i have a button
Load IT!
on the script tag:
function loadTheFile() {
var script = $("<script><\/script>");
script.attr("type", "text/javascript");
script.attr('src','http://www.thisismyexternalloadingjsfile"');
$('body').append(script);
alert("done! the file has been loaded");
}
the script well, when loaded will automatically have a modal box.
but the problem is, my alert seems to fire first than what is one the script
so how will i know if i have finished to load the script?
update for the first attempt to answer:
function loadTheFile() {
var script = $("<script><\/script>");
script.attr("type", "text/javascript");
script.attr('src','http://www.thisismyexternalloadingjsfile"');
$('body').append(script);
$(document).ready(function() {
alert("done! the file has been loaded")};
}
same problem
alert does indeed run before the script has been loaded. All that appending the script tag to the page does is append the script tag to the page. Then the browser has to download the script and, once received, run it. That will be after your loadTheFile function has exited.
So you need to get a callback when the script has actually be loaded and run. This is more standard than it used to be, but still has some cross-browser hassles. Fortunately for you, jQuery's already solved this problem for you (since you're using jQuery already):
function loadTheFile() {
$.getScript('http://www.thisismyexternalloadingjsfile"')
.then(function() {
alert("done! the file has been loaded");
});
}
Re your comment:
but my script file has data-* attributes
Assuming you're talking about data-* attributes on the script tag, then you'll have to do a bit more work, but it's still fairly straightfoward:
function loadTheFile() {
var load = $.Deferred();
var script = document.createElement('script');
script.src = 'http://www.thisismyexternalloadingjsfile"';
// No need for `type`, JavaScript is the default
script.setAttribute("data-foo", "bar");
script.onreadystatechange = function() {
if (script.readyState === "loaded") {
load.resolve();
}
};
script.onload = function() {
load.resolve();
};
load.then(function() {
alert("done! the file has been loaded");
});
document.body.appendChild(script); ;// Or wherever you want to put it
}
The onreadystatechange bit is to handle older versions of IE.
Rather than forge the script with text and jQuery, just use native Javascript:
var s = document.createElement('script');
s.onload = scriptLoaded;
s.src = '/path/to/my.js';
document.body.appendChild(s);
function scriptLoaded() {
console.log('Script is loaded');
}
Try something along these lines:
Your main page:
function whenScriptIsReady(){
alert('This function is called when the other script is loaded in!')
}
function loadTheFile() {
var script = $("<script><\/script>");
script.attr("type", "text/javascript");
script.attr('src','myotherjs.js');
$('body').append(script);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Load IT!
myotherjs.js:
alert('This will automatically run when the JS is loaded in!');
whenScriptIsReady();
JavaScript is executed asynchronously, so you alert will be executed before the browser can load the new script. If you want to execute logic after the script has been loaded, you could add an event listener to your script that will call the function 'loadFunc` once the script load is completed:
var loadFunc = function() {
alert("External Javascript File has been loaded");
};
//Other browsers trigger this one
if (script.addEventListener)
script.addEventListener('load', loadFunc, false);

Loading scripts dynamically

I'm loading a few YUI scripts dynamically in my code in response to an Ajax request. The DOM and the page is fully loaded when the request is made - it's a response for an user event.
I add the <scripts> tag to head as children, but I stumbled in a few problems:
I add two YUI scripts hosted at the Yahoo! CDN and an inlined script of my own responsible for creating object, adding event listeners and rendering the YUI widgets. But I when my script run the YUI scripts are not loaded yet giving me errors and not running as I expect.
There's a way to only run my script (or define a function to be run) when YUI scripts are fully loaded?
Have you tried an onload event?
Edited:(thanks Jamie)
var script = document.createElement("script");
script.type = "text/javascript";
script.src = src;
//IE:
if(window.attachEvent && document.all) {
script.onreadystatechange = function () {
if(this.readyState === "complete") {
callback_function(); //execute
}
};
}
//other browsers:
else {
script.onload = callback_function; //execute
}
document.getElementsByTagName("head")[0].appendChild(script);
If you're using YUI 2.x I highly recommend using the YUI Get utility, as it's designed to handle just this sort of a problem.
If you are loading multiple individual script files from the Yahoo! CDN, you'll need to makes sure both are loaded before executing your dependent code. You can avoid this using the combo handler. See the Configurator to get what the script url should be to load both/all needed YUI files from one url.
http://developer.yahoo.com/yui/articles/hosting/
With that in mind, assuming you must load the YUI files asynchronously, you should use an onload/onreadystatechange handler as noted by digitalFresh.
I would recommend the following pattern, however:
(function (d) {
var s = d.createElement('script'),
onEvent = ('onreadystatechange' in s) ? 'onreadystatechange' : 'onload';
s[onEvent] = function () {
if (("loaded,complete").indexOf(this.readyState || "loaded") > -1) {
s[onEvent] = null;
// Call your code here
YAHOO.util.Dom.get('x').innerHTML = "Loaded";
}
};
// Set the src to the combo script url, e.g.
s.src = "http://yui.yahooapis.com/combo?2.8.1/...";
d.getElementsByTagName('head')[0].appendChild(s);
})(document);
You could use a setTimeout() to run some function that just checks if it's loaded - check something like
if (typeof YUI_NAMESPACED_THING !== "undefined") runCode()
EDIT Thanks, CMS
If I understand this correctly, your ajax response with this:
<script href="yui-combo?1"></script>
<script href="yui-combo?2"></script>
<p>some text here</a>
<script>
// using some of the components included in the previous combos
// YAHOO.whatever here...
</script>
If this is the case, this is a clear case in which you should use dispatcher plugin. Dispatcher will emulate the browser loading process for AJAX responses. Basically it will load and execute every script in the exact order.
Best Regards,
Caridy

Injecting jQuery into a page fails when using Google AJAX Libraries API

I'd like to inject jQuery into a page using the Google AJAX Libraries API, I've come up with the following solution:
http://my-domain.com/inject-jquery.js:
;((function(){
// Call this function once jQuery is available
var func = function() {
jQuery("body").prepend('<div>jQuery Rocks!</div>');
};
// Detect if page is already using jQuery
if (!window.jQuery) {
var done = false;
var head = document.getElementsByTagName('head')[0];
var script = document.createElement("script");
script.src = "http://www.google.com/jsapi";
script.onload = script.onreadystatechange = function(){
// Once Google AJAX Libraries API is loaded ...
if (!done && (!this.readyState || this.readyState == "loaded" || this.readyState == "complete")) {
done = true;
// ... load jQuery ...
window.google.load("jquery", "1", {callback:function(){
jQuery.noConflict();
// ... jQuery available, fire function.
func();
}});
// Prevent IE memory leaking
script.onload = script.onreadystatechange = null;
head.removeChild(script);
}
}
// Load Google AJAX Libraries API
head.appendChild(script);
// Page already using jQuery, fire function
} else {
func();
}
})());
The script would then be included in a page on a separate domain:
http://some-other-domain.com/page.html:
<html>
<head>
<title>This is my page</title>
</head>
<body>
<h1>This is my page.</h1>
<script src="http://my-domain.com/inject-jquery.js"></script>
</body>
</html>
In Firefox 3 I get the following error:
Module: 'jquery' must be loaded before DOM onLoad! jsapi (line 16)
The error appears to be specific to the Google AJAX Libraries API, as I've seen others use a jQuery bookmarklet to inject jQuery into the current page. My question:
Is there a method for injecting the Google AJAX Libraries API / jQuery into a page regardless of the onload/onready state?
If you're injecting, it's probably easier to request the script without using the google loader:
(function() {
var script = document.createElement("script");
script.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js";
script.onload = script.onreadystatechange = function(){ /* your callback here */ };
document.body.appendChild( script );
})()
I found this post after we figured out a different solution. So for some reason, if you can't use the accepted solution, this one seem to work fine:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
if (typeof jQuery == 'undefined') {
// jQuery hasn't been loaded... so let's write it into the head immediately.
document.write('<script type="text/javascript" src="/jquery-1.3.2.min.js"><\/script>')
}
</script>
One issue with the accepted solution is that you're forced to put all your code that you want to run on the page into your callback function. So anything that needs jQuery (like plugins) need to be called from that function. AND, all your other included JS files that require jQuery are dependent upon jQuery being loaded BEFORE all the other scripts fire.
I Got It Working!!!!! I figured it out by looking in the application playground....
Here is the wrapper to start using jquery.... Put an alert in the function to see it work
google.load("jquery", "1.4.2");
function OnLoad(){
$(function(){
});
}
google.setOnLoadCallback(OnLoad);
You can use less painful solution to inject jquery (the lastest stable version available) to any page.
jQuerify - Chrome extension used to inject jQuery (the latest stable version available) into any web page (even HTTPS)"

Categories

Resources