How to find a file is available on server in jQuery? - javascript

I am trying to load a java script file from another server to my web page using java script code document.write method. like,
document.write("<script type='text/javascript' src='http://www.mydomain.com/js/myscript.js'></script>");
But the respective path does not has the myscript.js so its throw 404 File not found error in browser error console.
How can I predict and avoid this kind of errors?
If possible to predict the error, I will display alternative message instead of calling missed js file functions.

Use JavaScript to load script:
function onReadyState() {
console.error("Unable to load file: "+ this.src + ". Please check the file name and parh.");
return false;
}
function addJS(path){
var e = document.createElement("script");
e.onerror = onReadyState;
e.src = path;
e.type = "text/javascript";
document.getElementsByTagName('head')[0].appendChild(e);
}
addJS('http://www.mydomain.com/js/myscript.js');

Try jQuery.getScript( url [, success(script, textStatus, jqXHR)] ) - you can set success and error handlers in it.

If the file requested is in your domain (as it seems from the question) just do a previous ajax call (with HEAD method) of that resource and check if the response status is 200 (ok) or 304 (Not modified)

try this approach
var js="ajax/test.js";
$.getScript(js) .done(function(script, textStatus) {
var script = document.createElement( 'script' );
script.type = 'text/javascript';
script.src = js;
document.body.appendChild(script);;
})
for more details: jQuery.getScript
Please note: Use javascript (not jQuery) to manipulate HTML DOM

Related

JSONP error callback without using Jquery

I'm using JSONP, without jquery, by doing something like this:
var scriptElement = document.createElement('script');
scriptElement.type = 'text/javascript';
scriptElement.src = url;
document.getElementsByTagName('head')[0].appendChild(scriptElement);
Where url is for calling my server. Is it possible to return error response (for example, 403) with a message to display, and display it?
I was able to catch the existence of an error by defining:
scriptElement.onerror = function (event) {
...;
};
But this way I'm not able to see the message got from the server.
I can't use jquery so I can't use $.ajax.fail.
Thanks!

Can't insert js programmatically if it uses document.write

I am trying to insert js files programmatically, using jquery and something like this:
var script = document.createElement( 'script' );
script.type = 'text/javascript';
script.src = 'http://someurl/test.js';
$('body').append(script);
It works fine, if test.js contains an alert or some simple code it works fine, but if the file test.js contains document.write, and the file including the js is hosted on another domain than test.js (or localhost), nothing happens and firebug shows the error :
A call to document.write() from an asynchronously-loaded external
script was ignored.
If the test.js and the file that include it are hosted on the same domain, on chrome it still wont work but on firefox the document.write gets executed fine but the page stays "loading" forever and sniffer show request to all the files with "pending" status.
What other methods to include js files programmatically could I try?
use innerHTML instead of using document,write.
and use following code to register script,
(function() {
var jq = document.createElement('script');
jq.type = 'text/javascript';
jq.async = true;
jq.src = 'http://someurl/test.js';
var s = document.body.getElementsByTagName('script')[0];
s.parentNode.insertBefore(jq, s);
})();
Document.write is ONLY for synchronous tasks when the html is loaded (for the very first time), never for asynchronous tasks like the one you are trying to do.
What you want to do is dynamically insert a <script> DOM element into the HEAD element. I had this script sitting around. As an example, it's a race condition, but you get the idea. Call load_js with the URL. This is done for many modern APIs, and it's your best friend for cross-domain JavaScript.
<html>
<head>
<script>
var load_js = function(data, callback)
{
var head = document.getElementsByTagName("head")[0];
var script = document.createElement("script");
script.type = "text/javascript";
script.src = data;
head.appendChild(script);
if(callback != undefined)
callback();
}
load_js("http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js");
setTimeout(function() {
$('body').html('loaded');
}, 1000);
</script>
</head>
<body></body>
</html>
There isn't anything wrong with your approach to inserting JavaScript. document.write just sucks a little bit. It is only for synchronous tasks, so putting a document.write in a separate script file is asking for trouble. People do it anyway. The solution I've seen most often for this is to override document.write.

load external javascript in rails

I would like to download javascript files in parallel via injecting the script element and the src of the file in js like so
:javascript
var script = document.createElement("script");
script.src = "/javascript/some_javascript_file.js";
script.type = "text/javascript"
$("head").append(script)
....
(using haml, jquery..)
in rails via firebug i get a 404 file not found which looks like this
GET http://localhost:3000/javascript/%5object%20HTMLScriptElement%5D 404 Not found
..i see that the other js files added via javascript_include_tag loading fine
GET http://localhost:3000/javascript/another_js_file.js?1221321321 ...
I know that rails adds a version number onto the js file for versioning. Is it not possible to load js dynamically like how i am doing for this reason? I also noticed that the script name is also obfuscated(%5object%20HTMLScriptElement%5D). Is there a rails way of doing this? I have looked online and could not find anything.
I just noticed that the url for the 404 is different from what i specified in the src. In the src i have "/rails/javascripts/javascript_file.js" but in the 404 error its listed as getting the file from http://localhost.admeld.com:3000/rails/some_namespace/%5Bobject%20HTMLScriptElement%5D
Edit:
The jquery getScript call worked.
$.getScript('/rails/javascripts/javascript_file.js', function(data, textStatus){
console.log(data); //data returned
console.log(textStatus); //success
console.log('Load was performed 0.');
});
Try this:
:javascript
var script = document.createElement("script");
script.src = "/javascript/some_javascript_file.js";
script.type = "text/javascript"
$("head").get(0).appendChild(script);

How to include jquery.js in another js file?

I want to include jquery.js in myjs.js file. I wrote the code below for this.
var theNewScript=document.createElement("script");
theNewScript.type="text/javascript";
theNewScript.src="http://example.com/jquery.js";
document.getElementsByTagName("head")[0].appendChild(theNewScript);
$.get(myfile.php);
There shows an error on the 5th line that is '$ not defined'. I want to include jquery.js and then want to call $.get() function in myjs.js file. How can I do this?
Please help me
Appending a script tag inside the document head programmatically does not necessarily mean that the script will be available immediately. You should wait for the browser to download that file, parse and execute it. Some browsers fire an onload event for scripts in which you can hookup your logic. But this is not a cross-browser solution. I would rather "poll" for a specific symbol to become available, like this:
var theNewScript = document.createElement("script");
theNewScript.type = "text/javascript";
theNewScript.src = "http://example.com/jquery.js";
document.getElementsByTagName("head")[0].appendChild(theNewScript);
// jQuery MAY OR MAY NOT be loaded at this stage
var waitForLoad = function () {
if (typeof jQuery != "undefined") {
$.get("myfile.php");
} else {
window.setTimeout(waitForLoad, 1000);
}
};
window.setTimeout(waitForLoad, 1000);
The problem is that the script doesn't load instantly, it takes some time for the script file to download into your page and execute (in case of jQuery to define $).
I would recommend you to use HeadJS. then you can do:
head.js("/path/to/jQuery.js", function() {
$.get('myfile.php');
});
Simple answer, Dont. The jQuery file
is very touchy to intruders so dont
try. Joining other files into jQuery
file will often cause errors in the JS
console, PLUS jQuery isn't initialized
until the file is loaded into main
document.
Sorry, scratch that. Didnt quite know what you were doing.
Try this:
var s = document.createElement('script');
s.type = 'text/javascript';
s.async = true;
s.src = 'http://domain.com/jquery.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(s);
I used this code before, and it worked:
var t=document;
var o=t.createElement('script');
o=t.standardCreateElement('script');
o.setAttribute('type','text/javascript');
o.setAttribute('src','http://www.example.com/js/jquery-1.3.2.js');
t.lastChild.firstChild.appendChild(o);

JavaScript Error occured with JSONP in bookmarklet

The following Error occured in FireBug Firefox3.5.2
Failed to load source for: http://example.com/
My bookmarklet is
javascript:(
function(){
window.callback = function(d){alert(d)};
var script = document.createElement('script');
script.setAttribute("type", "text/javascript");
script.setAttribute("charset", "UTF-8");
script.setAttribute("id", (new Date()).getTime());
script.src="http://example.com/api/function.php?callback=window.callback";
document.body.appendChild(script);
}
)();
callback is:
window.cb && window.cb({"key":"value"});
What's wrong?
If you're really loading from a PHP page, I would make sure that page is returning a text/javascript MIME type.

Categories

Resources