loading js files dynamically via another js file? - javascript

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/

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

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.

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