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) { ... });
Related
Not able to load the script file inside another script file when using $.getJson(); inside the loaded script files.
Consider fisrt.html:
<script>
$.getScript("second.js",function(){
// some code here
});
</script>
my second js file is like:
second.js:
$.getJSON("somefile.json",function(){
});
When remove the $.getJSON from the second.js the files load perfectly without any problem.
How can I load the my json file with $.getJSON?
EDIT:
complte json calling:
$.getJSON('js/offline.json', function(data) {
alert("success");
}.error(function(data){
alert(JSON.stringify(data));
});
You're trying to use the promise and standard callback API at the same time. Here's what you want.
$.getJSON("js/offline.json")
.done(function (data) {
alert(data);
})
.fail(function (err) {
alert(err);
});
You can try using the following function:
function loadScript(url, callback)
{
// Adding the script tag to the head as suggested before
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
// Then bind the event to the callback function.
// There are several events for cross browser compatibility.
script.onreadystatechange = callback;
script.onload = callback;
// Fire the loading
head.appendChild(script);
}
Also:
1. Remove the : in the second script to replace with ;
2. make sure that somefile.json exists in the same directory.
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.
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.
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 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/