Overwriting the URL at runtime through JS in IE11 - javascript

I have a page that loads some external script (Ex: abc.com/test.js) by default.
I will create a bookmarklet that will overwrite that external script with a new URL (Ex: def.com/newTest.js), when the page is loading.
Can any body let me know on how to overwrite the URL at run time in IE11 ...
Any help would be highly appreciated.

Something like following (you can merge it to the one line for bookmarklet):
var s = document.querySelector("script[src='abc.com/test.js']");
s.parentNode.removeChild(s);
s = document.createElement('script');
s.src = "def.com/newTest.js";
document.body.appendChild(s)

jQuery Version:
$(document).on('ready', function(){
$('head').find('script[src="abc.com/test.js"]').attr('src','def.com/newTest.js');
});

Related

Reference JS file in JS file

I have a Js function that I would like to:
Reference another js file
Pull a function out.
I would like to do this JS side and not reference on the actual page as I need this process to happen dynamically.
var h = document.getElementsByTagName('head')[0],
s = document.createElement('script');
s.type = 'text/javascript';
s.onload = function () { document.getElementById('hello').innerText = h.innerText; };
s.src = 'http://html5shiv.googlecode.com/svn/trunk/html5.js';
h.appendChild(s);
see: http://jsbin.com/uhoger
If you're working with the browser, jQuery has an helper function for it, $.getScript.
The only option I can think of is to dynamically insert a new script tag into the page targeting your desired script from your initial javascript. Just have your initial script insert the new <script> tag on load, or upon request and then test for availability.

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

Is there a way to refresh just the javascript include while doing development?

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/

An other way to load a js file in js code

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

loading js files dynamically via another js file?

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/

Categories

Resources