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 ?
Related
I got problem loading dynamic JS in my script, so here the case, I have a plan to build android app with local webview something like webView.loadUrl("file:///android_asset/filename.html");
Everything work fine since its only html file, but the problem came when I need to read local js contain array data that need to read by other js file.
To make it clear,
I have 100++ data_1.js data_2.js etc who contain something like
data = [{
no1:"xxx",
no1:"xxx",
no3:"xxx",
..
}]
Those data will be read by one of my js script and display it on html file, basically I only need 1 data each time the page open, so its like when I open file://.../folder/file.html?no=1 it will only need to read data_1.js, file://.../folder/file.html?no=2 it will only need to read data_2.js
This is what I try to do.
#1
Using getScript("assets/data/data_"+number+".js");
This work when we use local server, when I access via localhost/folder/file.html?no=1 its work, but when I access file://..../folder/file.html?no=1 it not load because cors block
#2
Using ajax, result same with #1
#3
Add all data_x.js directly in file.html
<script src="folder/data_1.js"></script>
<script src="folder/data_2.js"></script>
<script src="folder/data_3.js"></script>
Its work when we access file://..../folder/file.html?no=1 but the page load very slow because need to include and load whole data_x.js (more than 100++)
Is there any other way to solve this problem?
Note: I don't want to connect to any server because I want the apps can be access offline so all data will be included inside the apps
You can make use of URLSearchParam in combination with createElement, which is similar to your solution #3 but only loads the file from parameter id.
So you can also make use of: webView.loadUrl("file:///android_asset/filename.html?id=N");
<html>
<body>
<script>
const urlParams = new URLSearchParams(window.location.search),
id = urlParams.get('id');
if (id != null) {
const script = document.createElement("script");
script.src = `folder/data_${id}.js`;
script.onload = function() {
// do something ...?
}
document.body.appendChild(script);
}
</script>
</body>
</html>
EDIT:
At least at desktop it works fine.
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);
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);
While doing development on a .js file I'd like to just refresh that file instead of the entire page to save time. Anyone know of any techniques for this?
Here is a function to create a new script element. It appends an incremented integer to make the URL of the script unique (as Kon suggested) in order to force a download.
var index = 0;
function refreshScript (src) {
var scriptElement = document.createElement('script');
scriptElement.type = 'text/javascript';
scriptElement.src = src + '?' + index++;
document.getElementsByTagName('head')[0].appendChild(scriptElement);
}
Then in the Firebug console, you can call it as:
refreshScript('my_script.js');
You'll need to make sure that the index itself is not part of the script being reloaded!
The Firebug Net panel will help you see whether the script is being downloaded. The response status should be "200 OK" and not "304 Not Modified. Also, you should see the index appended in the query string.
The Firebug HTML panel will help you see whether the script element was appended to the head element.
UPDATE:
Here is a version that uses a timestamp instead of an index variable. As #davyM suggests, it is a more flexible approach:
function refreshScript (src) {
var scriptElement = document.createElement('script');
scriptElement.type = 'text/javascript';
scriptElement.src = src + '?' + (new Date).getTime();
document.getElementsByTagName('head')[0].appendChild(scriptElement);
}
Alexei's points are also well-stated.
I suggest you to use Firebug for this purpose.
See this video, it helped me a lot.
http://encosia.com/2009/09/21/updated-see-how-i-used-firebug-to-learn-jquery/
If you're talking about the unfortunate case of client-side/browser caching of your .js file, then you can simply version your .js file. You can:
Rename the .js file itself (not preferred)
Update the include line to reference yourfile.js?1, yourfile.js?2, etc.. Thus forcing the browser to request the latest version from the server. (preferred)
Unfortunately, you have to refresh the web page to see edits to your JavaScript take place. There is no way that I know of to edit JavaScript in "real-time" and see those edits effect without a refresh.
You can use Firebug to insert new JavaScript, and make real-time changes to DOM objects; but you cannot edit JavaScript that has already been run.
If you just fed up refilling the forms while developing just use form recover extensions like this one https://addons.mozilla.org/ru/firefox/addon/lazarus-form-recovery/
I opened a javaScript file in a javaScript time....
document.write("<script src='newnote.js' type='text/javascript'></script>");
is there an other way to load the js in js code..?
(this file is for loading a popup menu js code , which is loaded after delay by clock js code ... so i want an othe way to loaded it)
When opening a JS file, its code is executed at once - functions are created, code is run, events are set. The only way to 'unload' a Javascript file is to manually undo all the code that has been run as a result of loading the unwanted file: setting all new functions, variables and prototype aditions to undefined (e.g. window.badFunction = undefined, unset all events, remove all new DOM elements..
If you wanted to unload another JS file every time when opening a page, it could in theory be done, but not very easily and if the loaded JS file should change, you would have to update your invalidating file.
What you did isn't like opening a local file in a programming language like C++ or Java. You don't need to close anything.
Is it possible that the script that you are adding to the page (in this case newnote.js) is causing the error you are experiencing?
Instead of the line you used starting with document.write use this instead:
var newnote = document.createElement('script');
newnote.src = "newnote.js";
newnote.type = "text/javascript";
document.documentElement.firstChild.appendChild( newnote );
If you still get your quotes error, then the code inside of newnote.js is messed up.
Don't think this was really what you were asking, but if you used the code I listed above you could then remove this file from your page by calling this:
document.documentElement.firstChild.removeChild( newnote );
One more thought:
If your path to newnote.js is not correct (because it is not in the same directory as the calling page) then the server would return a 404 error page instead of the file. If your browser tried to execute it like javascript, it could throw an error. Try supplying the full URL: http://yoursite.com/js/newnote.js or a root relative one: /js/newnote.js
you are not opening a javascript file, in fact you cannot open any file from local file system, so there is no question of closing. You are inserting a script tag replacing all contents of the document. This would result in fetching newnote.js using the current url with newnote.js replacing anything after last slash.
To include a script you could try this:
var s = document.createElement('script');
s.src = 'newnote.js';
s.type = 'text/javascript';
var head = document.getElementsByTagName('head')[0]
head.appendChild(s);
or like that:
document.write("<script type='text/javascript' src='newnote.js'><\/sc" + "ript>");