Can't use jquery after loading it dynamically - javascript

I'm loading data.js into my a.html page.
In my data.js, i am checking if a.html has jquery and loading it if not. Right after loading jquery i am making an ajax call but i am getting
$ is not defined
exception.
Here is my data.js
if(typeof jQuery=='undefined') {
var headTag = document.getElementsByTagName("head")[0];
var jqTag = document.createElement('script');
jqTag.type = 'text/javascript';
jqTag.src = 'http://localhost:8001/jquery-min.js';
headTag.appendChild(jqTag);
}
var url = 'http://127.0.0.1:5000';
$.ajax({
url: url,
success: function(data) {
$("#" + containerId).html(data);
},
error: function(e) {
console.log(e.message);
}
});
From developer console, i can see jquery is loaded. I can see it in both Resources and head tag.

The jQuery (and $ thus) isn't loaded yet when you make the AJAX call since you only just added the script tag to your DOM. After that it starts the downloading. Instead you should bind the onload event of script tag and perform the actions after it has been loaded.
Example
jqTag.onload = function() {
var url = 'http://127.0.0.1:5000';
$.ajax({
url: url,
success: function(data) {
$("#" + containerId).html(data);
},
error: function(e) {
console.log(e.message);
}
});
}
jqTag.src = 'http://localhost:8001/jquery-min.js';

change this Line :
if(typeof jQuery=='undefined')
to
if(typeof jQuery== undefined ) {

Related

Implement 'error' callback for Dynamically loaded javascript file

I am loading javascript dynamically and accessing its variable. I checked the second answer from this question and the following code works beautifully.
include = function (url, fn) {
var e = document.createElement("script");
e.onload = fn;
e.src = url;
e.async=true;
document.getElementsByTagName("head")[0].appendChild(e);
};
include("test.js",function(){
console.log(foo);
});
QUESTION: I want to have a onFailure callback function as well that allows me to process code in case
The internet is down.
The filename is not accessible (eg: incorrect path)
Will appreciate if someone can guide me to the right direction.
Thanks
The MDN page for the HTMLScriptElement has a good example which you can build off.
function loadError (oError) {
throw new URIError("The script " + oError.target.src + " is not accessible.");
}
function importScript (sSrc, fOnload) {
var oScript = document.createElement("script");
oScript.type = "text\/javascript";
oScript.onerror = loadError;
if (fOnload) { oScript.onload = fOnload; }
document.currentScript.parentNode.insertBefore(oScript, document.currentScript);
oScript.src = sSrc;
}
I think the simplest solution is to actually use an XMLHttpRequest. This gives you access to the status of the request after it completes, where the "load" event does not. For simplicity, I'll illustrate with jQuery, but this can be written in vanilla javascript as well.
$.ajax({
url:"myfile.js",
method:"GET",
dataType:"html",
success: function(data, status, jqxhr) {
console.log("It worked");
// This can be very dangerous. Make sure you trust script source.
var newScript = $("<script>").html(data);
$('body').append(newScript);
},
error: function(jqxhr, status, error) {
console.log("Oh no!");
}
});
More on the jQuery ajax request here.

Load external javascript file after onload()

I use this in the head tag:
<script src="js/lightbox.js"></script>
Is it possible to remove this off the header and load this file with onload()?
<body onload="...">...</body>
Note: This is not a function, it's an external js file with several functions.
Thanks!
<script>
function loadJS(src, callback) {
var s = document.createElement('script');
s.src = src;
s.async = true;
s.onreadystatechange = s.onload = function() {
var state = s.readyState;
if (!callback.done && (!state || /loaded|complete/.test(state))) {
callback.done = true;
callback();
}
};
document.getElementsByTagName('head')[0].appendChild(s);
}
loadJS('/script/script.js', function() {
// put your code here to run after script is loaded
});
</script>
I still think its better to load in jQuery and use $.getScript instead as you have lots of goodies there.
Can call this on body load
onload="blabla();"
function blabla()
{
$.getScript( 'url to your js file', function( data, textStatus, jqxhr ) {
// do some stuff after script is loaded
});
}
You can learn more here
Source
If you want to do it without jQuery, use this
function addScript(filename)
{
var scriptBlock=document.createElement('script')
scriptBlock.setAttribute("type","text/javascript")
scriptBlock.setAttribute("src", filename)
document.getElementsByTagName("head")[0].appendChild(scriptBlock)
}
and call it with <body onload="addScript('myFile.js')". If you have multiple files to load, you could put in a wrapper, that adds all the files you want.
Use $(document).ready()
and from this function load javascript. It sounds crazy but can be done. please follow http://www.javascriptkit.com/javatutors/loadjavascriptcss.shtml
var JS = {
load: function(src, callback) {
var script = document.createElement('script'),
loaded;
script.setAttribute('src', src);
if (callback) {
script.onreadystatechange = script.onload = function() {
if (!loaded) {
callback();
}
loaded = true;
};
}
document.getElementsByTagName('head')[0].appendChild(script);
}
};
// Example with callback
JS.load("http://www.someawesomedomain.com/some.js", function() {
//Do your thing.
});

Call a script along with parameters from if statement using jQuery

I have a script that I have no control over and is on another domain. The default procedure is to just include it in a script tag and it runs fine.
I don't want to run it by default so I have an if statement and if true I want to run the script.
So default option is:
<script src="http://domain/site/script?Id=12345&delayMs=2000&stayMs=10000&chance=0.1" type="text/javascript" ></script>
I taught I could just use jQuery.getScript() to get it to run the above url but this does not work. I do not know the correct link to the actual script and functions contained so I cannot getScript and call functions.
Any ideas would help.
Regards
Brian
Since you're having cross domain issues, try this ($.getScript() is just a shorthand for this anyway, with the exception of crossDomain: true).
$.ajax({
url: 'http://domain/site/script?Id=12345&delayMs=2000&
stayMs=10000&chance=0.1',
crossDomain: true,
dataType: 'script',
success: function () {
// script is loaded
},
error: function () {
// handle errors
}
});
Another solution you can try using pure JS:
function loadScript(src, callback)
{
var s,
r,
t;
r = false;
s = document.createElement('script');
s.type = 'text/javascript';
s.src = src;
s.onload = s.onreadystatechange = function() {
//console.log( this.readyState );
//uncomment this line to see which ready states are called.
if ( !r && (!this.readyState || this.readyState == 'complete') )
{
r = true;
callback();
}
};
t = document.getElementsByTagName('script')[0];
t.parent.insertBefore(s, t);
}
Usage:
var url = 'http://domain/site/script?Id=12345&delayMs=2000&
stayMs=10000&chance=0.1';
loadScript(url, function(){
console.log('script loaded');
});

My ajax call is not working in Chrome and Firefox

Hi My ajax call is not working in chrome and firefox but it is in Safari.
I am not able to figure it out as it is working on all browsers locally.
My site is recently had SSl certificate.Is that something causing problem?
I am not sure. For reference below is my Ajax function
<script type="text/javascript">
//<![CDATA[
$(function () {
$("#selectReport").hide();
$("select#countryId").change(function () {
var manu = $("#manufacturerId option:selected").text();
$("#Manufacturer").val(manu);
$("#selectReport").show();
});
$("select#reportId").change(function (e) {
e.preventDefault();
var country = $("#countryId option:selected").text();
$("#CountryName").val(country);
});
$("select#reportId").change(function (event) {
event.preventDefault();
var reportName = $("#reportId option:selected").text();
var manufacturer = $("#Manufacturer").val();
var countryName = $("#CountryName").val();
var theUrl = "/Reports/GetReport/" + reportName + "/" + manufacturer + "/" + countryName;
$.ajax({
url: theUrl,
type: 'get',
success: function (data) {
alert("I am success");
$('#ajaxOptionalFields').html(data);
},
error: function () {
alert("an error occured here");
}
});
});
});
//]]>
</script>
seems you didn't load the Jquery Lib,
http://jquery.com/download/ download Jquery lib and put it in your js folder and load it.. then it should understand what "$" is... in Jquery i always start script like:
$( document ).ready(function() {
//do sth here
});
Instead of copying link directly please copy relative paths so that it will be secured.
For example copy http://code.highcharts.com/highcharts.js in higncharts.js and point that to relative path.

Firefox extension: Add javascript to webpage

I'm working on a FireFox extension that listens to onStateChange. When the current document has been loaded it should insert a script to the page and it should be able to call the script on a button event.
Now I am able to add a button to all webpages by using:
nsCOMPtr<nsIDOMElement> NewInputElementTest;
rv = htmlDoc->CreateElement(NS_LITERAL_STRING("input"),getter_AddRefs(NewInputElementTest));
rv = NewInputElementTest->SetAttribute(NS_LITERAL_STRING("type"),NS_LITERAL_STRING("button"));
rv = NewInputElementTest->SetAttribute(NS_LITERAL_STRING("value"),NS_LITERAL_STRING("hummer"));
rv = body->AppendChild(NewInputElementTest,getter_AddRefs(AddedNewInputElement2));
The button is displayed correctly.
I wish to use the same procedure to add a SCRIPT to the page, like so:
rv = htmlDoc->CreateElement(NS_LITERAL_STRING("script"),getter_AddRefs(NewInputElement));
rv = NewInputElement->SetAttribute(NS_LITERAL_STRING("type"),NS_LITERAL_STRING("text/javascript"));
rv = NewInputElement->SetAttribute(NS_LITERAL_STRING("text"),NS_LITERAL_STRING("alert('hello world!')"));
rv = body->AppendChild(NewInputElement,getter_AddRefs(AddedNewInputElement));
All functions return success, but no script is added to the page. No alert is displayed, and if i insert a function and call it from the button.onclick then the FireFox log displayes that the function is not available.
If I use the exact same procedure from a javascript inside the html page, then it works find and the alert pops up.
Do I need to do anything to enable the script from my extension or why is the script not available from the button or anywhere else?
I hate to say it after you created a bunch of code, but check out Greasemonkey: https://addons.mozilla.org/en-US/firefox/addon/748
It'll probably handle a lot of your work for you.
Yes, sounds like you're tryin to re-invent the wheel. Use Greasemonkey as Oren suggested.
Here is a Greasemonkey script that I use to load external JS framework (Prototype and Scriptaculous in this case) load any number of external files (js and css) into a page.
// ==UserScript==
// #name External Loader
// #namespace http://ifelse.org
// #description Loads external JS and CSS
// #include http://*.yoursitedomainetc.com/*
// ==/UserScript==
var hasPrototype = ('Prototype' in unsafeWindow);
var hasEffects = ('Effect' in unsafeWindow);
function _require(url, isCSS) {
if (isCSS) {
var script = document.createElement('link');
script.setAttribute('type', 'text/css');
script.setAttribute('rel', 'stylesheet');
script.setAttribute('href', url);
} else {
var script = document.createElement('script');
script.setAttribute('type', 'text/javascript');
script.setAttribute('charset', 'UTF-8');
script.src = url;
}
document.getElementsByTagName('head')[0].appendChild(script);
}
// Load prototype; shouldn't get here because it is already on the page
if ( !hasPrototype ) {
_require('http://path.com/to/prototype/1.6.0.2/prototype.js');
}
// Load scriptaculous effects if it's not already loaded
if ( !hasEffects ) {
_require('http://path.com/to/scriptaculous/1.8.1/effects.js');
}
// Add greasemonkey ajax object
// Copies format of Prototype Ajax.Request to
// Allow to easily swap out at a later point (i.e. no longer FF plugin)
unsafeWindow.Remote = new Object;
unsafeWindow.Remote.Ajax = function(url, options) {
if (options.onCreate) {
options["onCreate"]();
}
var request = {
method: options.method || 'get',
url: url + ('?' + unsafeWindow.Object.toQueryString(options.parameters) || ''),
onload: function(response) {
if (response.status == 200)
options["onComplete"](response);
options["onSuccess"]();
},
onerror: options.onFailure || null
};
window.setTimeout(GM_xmlhttpRequest, 0, request);
};
// Load these External files
_require('http://path/to/anything/and/dont/cache/it.js' + '?cache=' + (new Date()).getTime());
_require('http://paht/to/something/else.css', true);
}

Categories

Resources