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);
Related
I'm doing something with .net core.
I have some jquery code that I use in almost every page and I want to set that specific code in one file and reuse it in others.
That common code has function that shoudl be called from others files.
Exactly I have some function for my modal pop up.
But I'm getting this error in browser "Failed to load resource: the server responded with a status of 404 (Not Found)"
My question is similar as on this link, but replies didnt help me
How to add jQuery in JS file
My code in VS
#*<script src="~/js/Event/OverViewNew.js"></script>
When I put all code in one file this works*#
$(document).ready(function () {
var script = document.createElement('script');
script.src = "~/wwwroot/js/Event/OverViewNew.js"; //doesn't work
//script.src = "~/js/Event/OverViewNew.js"; doesnt work
script.type = 'text/javascript';
document.head.appendChild(script);
//document.getElementsByTagName('head')[0].appendChild(script);
var script2 = document.createElement('script');
script2.src = '~/wwwroot/js/Helper/Modal.js'; //doesn't work
//script2.src = '~/js/Helper/Modal.js'; //doesn't work
script2.type = 'text/javascript';
document.head.appendChild(script2);
//document.getElementsByTagName('head')[1].appendChild(script2);
});
for a project I need to check the Response Code of a dynamically added JS into DOM. So Code looks basically like this one:
var newScript = document.createElement("script");
newScript.src = "http://www.example.com/dynamic-XXX.js";
target.appendChild(newScript);
The XXX will change and I am loading the File from Google Cloud Storage. So if I have a 200, everything is fine. But I need to check if I have 201 Status Code.
Any Ideas how to solve this in a nice way ?
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
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.
is there anyway to load other JS files from within a single JS file. I would like to point my individual pages "ITS" js file and that js file would load jquery, other js files.
I know i can just pop all these into the html i.e.
I was thinking of separations of concerns so i was wondering if anything exists already without me reinventing the wheel....
That i would just need to edit home.js to change what other js (jquery etc) are loaded for home.htm ... home.htm would just point to home.js
Thanks
You can take a look at dynamic script loading. Here's an excerpt from the article:
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'helper.js';
head.appendChild(script);
For external domain JS link
var loadJs = function(jsPath) {
var s = document.createElement('script');
s.setAttribute('type', 'text/javascript');
s.setAttribute('src', jsPath);
document.getElementsByTagName('head')[0].appendChild(s);
};
loadJs('http://other.com/other.js');
For same domain JS link (Using jQuery)
var getScript = function(jsPath, callback) {
$.ajax({
dataType:'script',
async:false,
cache:true,
url:jsPath,
success:function(response) {
if (callback && typeof callback == 'function') callback();
}
});
};
getScript('js/other.js', function() { functionFromOther(); });
This is similar to Darin's solution, except it doesn't make any variables.
document.getElementsByTagName('head')[0].appendChild(document.createElement("script")).src = "helper.js";
I'd suggest you take a look at labJS. It's a library made specifically to load Javascript. As they say..."The core purpose of LABjs is to be an all-purpose, on-demand JavaScript loader, capable of loading any JavaScript resource, from any location, into any page, at any time."
See the labJS home page for more information.
Google offers centrally hosted versions of the major javascript libraries like jQuery. They can be dynamically loaded using the google loader.
http://code.google.com/apis/ajaxlibs/documentation/