Not able to load the script file inside another script file - javascript

Not able to load the script file inside another script file when using $.getJson(); inside the loaded script files.
Consider fisrt.html:
<script>
$.getScript("second.js",function(){
// some code here
});
</script>
my second js file is like:
second.js:
$.getJSON("somefile.json",function(){
});
When remove the $.getJSON from the second.js the files load perfectly without any problem.
How can I load the my json file with $.getJSON?
EDIT:
complte json calling:
$.getJSON('js/offline.json', function(data) {
alert("success");
}.error(function(data){
alert(JSON.stringify(data));
});

You're trying to use the promise and standard callback API at the same time. Here's what you want.
$.getJSON("js/offline.json")
.done(function (data) {
alert(data);
})
.fail(function (err) {
alert(err);
});

You can try using the following function:
function loadScript(url, callback)
{
// Adding the script tag to the head as suggested before
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
// Then bind the event to the callback function.
// There are several events for cross browser compatibility.
script.onreadystatechange = callback;
script.onload = callback;
// Fire the loading
head.appendChild(script);
}
Also:
1. Remove the : in the second script to replace with ;
2. make sure that somefile.json exists in the same directory.

Related

How to add a script tag dynamically using javascript and detect if the script failed to load the file?

I know how to add a script tag to the body or head using append functions. But if the file (example.js) that I am trying to add is not present, it gives an error. How do I detect if this happens?
script elements have load and error events you can listen to.
Run whatever your dependent code is in a load event handler and do something else in error handler
Example loading jQuery :
var jQurl='https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js'
var s = document.createElement('script');
s.src = jQurl;
s.onerror = function(err) {
console.log(err)
}
s.onload = init;
document.head.appendChild(s);
function init(){
console.log('jquery version=', jQuery.fn.jquery)
$('body').append('<h3>Loaded!</h3>');
}
I think you could do something like the following:
script = document.createElement('script');
script.type = 'text/javascript';
script.onerror = () => {
// Whatever you want to do in case the load fails
};
script.src = '...' // your src for the script
// After this, append the script to wherever you want in the HTML document
Hope it helps!

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

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

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.

How to add JavaScript code in page header?

Can anyone please guide how can I add a javascript block to page header at run-time?
I want to link an external js file to header at run time.
If you want to load a script at run time with jquery you could use the ajax function:
$.ajax({
url: 'http://example.org/myscript.js',
dataType: 'script',
async: false
});
You need to look at this page that explains On Demand Javascript.
Specifically on this function:
function ensureUploadScriptIsLoaded() {
if (self.uploadScript) { // Already exists
return;
}
var head = document.getElementsByTagName("head")[0];
script = document.createElement('script');
script.id = 'uploadScript';
script.type = 'text/javascript';
script.src = "upload.js";
head.appendChild(script);
}
CommonJS also specifies a way to load scripts and the Dojo Toolkit implements it.
You should take a look at require function.
Example: require(["a/b"], function(b) { ... });

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);

Categories

Resources