How to include jquery.js in another js file? - javascript

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

Related

Overwriting the URL at runtime through JS in IE11

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

Chrome console behaviour

I am injecting through console jquery:
var jq = document.createElement('script');
jq.src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js";
document.getElementsByTagName('head')[0].appendChild(jq);
jQuery.noConflict();
Then I am using some jquery command
$('.first').position()
document.elementFromPoint(xPosition, yPosition).click();
After emulating click page in browser reloading. And than $('.first') allways return []; But on the page there are a lot of tags with class 'first'. It seems that console waiting for updating? Or what?
The appendChild is loading a script element into the DOM, that script tag then goes and downloads the file set to its src property. But this download takes time. It's asynchronous.
var jq = document.createElement('script');
jq.src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js";
document.getElementsByTagName('head')[0].appendChild(jq);
So when you attempt to access jQuery immediately after in your javascript, that file hasn't been downloaded yet. Imagine that the file took an hour to download. You'd need to wait to be notified that the file had finished downloading before using that code. There's a number of ways to think about this, like using an interval to check if the global variable is there, but I think the simplest is just to use an onload event.
var jq = document.createElement('script');
jq.src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js";
jq.onload = function(){
//do stuff using jquery
}
document.getElementsByTagName('head')[0].appendChild(jq);

Javascript to load another js file

I am trying to load another JS file from a JS file.
From my JavaScript file run.js, I have the following:
document.write("<script type='text/javascript' src='my_script.js'></script>");
alert(nImages);
In side my_script.js I have the following:
<SCRIPT language="JavaScript" type="text/javascript">
<!--
nImages = 6;
//-->
</SCRIPT>
But I can't seem to get it to alert the nImages from my_script.js file.
You could do this:
var script = document.createElement('script');
script.src = 'my_script.js';
script.type = 'text/javascript';
script.onload = function () {
alert(nImages);
};
document.getElementsByTagName('head')[0].appendChild(script);
You should not use HTML inside of your script file. Your script file my_script.js should have only this in it.
nImages = 6;
Additional note: you don't need language="JavaScript" or the <!-- or //-->. Those are old conventions not needed for modern browsers (even IE6). I'd also avoid using document.write() in your JS as it has performance implications. You may want to look at a library such as RequireJS which provides a better way to load other JS files in the page.
I also have a code snippet on Github inspired by Steve Souders that loads another file via straight JS.
var theOtherScript = 'http://example.com/js/script.js';
var el = document.createElement('script');
el.async = false;
el.src = theOtherScript;
el.type = 'text/javascript';
(document.getElementsByTagName('HEAD')[0]||document.body).appendChild(el);
This will append the other script to the element (if it exists) or the of the page.
Javascript files should not have HTML in them. They should consist entirely of Javascript code, so my_script.js should contain only:
nImages = 6;
This still won't work because when you write the new script tag into the document it doesn't run immediately. It is guaranteed that run.js finishes running before my_script.js starts, so nImages is undefined when you alert it and then becomes 6 later. You'll see that this works:
document.write("<script type='text/javascript' src='my_script.js'></script>");
function call_on_load(){
alert(nImages);
}
If the contents of my_script.js are:
nImages = 6;
call_on_load();
Edit
Since you said in a comment that you can not edit my_script.js you can do this although it is not nearly as nice a solution:
// Force nImages to be undefined
var undefined;
window.nImages = undefined;
document.write("<script type='text/javascript' src='my_script.js'></script>");
(function is_loaded(cb){
if(typeof window.nImages == 'undefined')
setTimeout(function(){ is_loaded(cb); }, 100);
else
cb();
})(function(){
// This is executed after the script has loaded
alert(nImages);
});
This is not a nice solution, however, since it will continue polling indefinitely if there is an error loading the script.
EDIT
You posted in a comment the file you want to include, which has the <SCRIPT at the top. This file is useless and you can't do anything about it client side. You'd have to write a server side script to load the file as text in which case you can just parse it for the value you want.

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.

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

Categories

Resources