How to call the function in this file? - javascript

I pasted the code given in this link to a file called md5.js.
http://www.webtoolkit.info/javascript-md5.html
I am not able to call the function in my below code. Please assist me.
function inc(filename)
{
var body = document.getElementsByTagName('body').item(0);
script = document.createElement('script');
script.src = filename;
script.type = 'text/javascript';
body.appendChild(script)
}
function CheckCaptcha()
{
var CaptchaWord="";
CaptchaWord = document.getElementById('studentusername').value;
inc("md5.js");
//Add MD5 function here.
}

You can try adding an event handler for the scripts onload and continuing your code from there.
e.g.
function inc(fname, callback)
{
var body = document.getElementsByTagName('body').item(0);
script = document.createElement('script');
script.src = filename;
script.type = 'text/javascript';
script.onload = callback;
body.appendChild(script);
}
function CheckCaptcha()
{
var CaptchaWord="";
CaptchaWord = document.getElementById('studentusername').value;
inc("md5.js", function() {
//Add MD5 function here.
});
}
The alternative to this approach (which will work far more rebustly as well) is to include the md5 script directly as opposed to using the inc function.
<script src="/path/to/md5.js" type="text/javascript"></script>
<script type="text/javascript">
function CheckCaptcha()
{
var CaptchaWord="";
CaptchaWord = document.getElementById('studentusername').value;
return md5(CaptchaWord); //or something
}
</script>

As onload doesnt work in ie you need to add onreadystatechange.
function inc(fname, callback)
{
var body = document.getElementsByTagName('body').item(0);
script = document.createElement('script');
script.src = filename;
script.type = 'text/javascript';
script.onload = callback;
script.onreadystatechange= function () {
if (this.readyState == 'complete') callback();
}
body.appendChild(script);
}
function CheckCaptcha()
{
var CaptchaWord="";
CaptchaWord = document.getElementById('studentusername').value;
inc("md5.js", function() {
//Add MD5 function here.
});
}

Related

How to determine that multiple js have been dynamically loaded

It's my js:
const map = new Map();
jsonData.list.forEach(function (item) {
if (!map.get(item.type)) {
usedLaterScript = document.createElement('script');
usedLaterScript.type = 'text/javascript';
usedLaterScript.src = 'js/component/' + item.type + '.js';
document.body.appendChild(usedLaterScript);
map.set(item.type, item.type);
}
});
jsonData:[{"type":"input"},{"type":"radio"},{"type":"select"}]
I want know when all js(like input.js,radio.js,select.js) was loaded,then I can do next
It could take time to load a dynamic added JS file. so you can bind a callback to the script tag like below, I load JQuery dynamically here.
<script>
let usedLaterScript = document.createElement('script');
usedLaterScript.src = 'https://code.jquery.com/jquery-3.3.1.min.js';
document.body.appendChild(usedLaterScript);
usedLaterScript.onload = function() {
if(allScriptsLoaded) {
allScriptsLoaded();
}
};
</script>
<script>
allScriptsLoaded = function() {
console.log("Jquery loaded",$);
}
</script>

Defer Loading of javascript for google page insights

I have a code for defer loading of javascript I am wondering if the code will load the scripts in order (JQuery.min first) according to where they are in the code ?
function downloadJSAtOnload() {
var element01 = document.createElement("script");
element01.src = "js/jquery.min.js";
document.body.appendChild(element01);
var element02 = document.createElement("script");
element02.src = "js/plugins.js";
document.body.appendChild(element02);
var element03 = document.createElement("script");
element03.src = "js/scripts.js";
document.body.appendChild(element03);
var element04 = document.createElement("script");
element04.src = "js/SmoothScroll.min.js";
document.body.appendChild(element04);
var element05 = document.createElement("script");
element05.src = "js/contact-form.js";
document.body.appendChild(element05);
}
if (window.addEventListener)
window.addEventListener("load", downloadJSAtOnload, false);
else if (window.attachEvent)
window.attachEvent("onload", downloadJSAtOnload);
else window.onload = downloadJSAtOnload;
If this doesn't load JQuery.min first and then the other js files how can you make JQuery.min the first script to load and then the rest after that has loaded?
Also I am guessing for example the contact-form.js will be one of the first to finish loading as it's small so this could cause the Uncaught ReferenceError: $ is not defined I'm guessing because the JQuery.min hasn't finished downloading so how would you solved this ? I'm guessing an listener / if finished loading load the others else wait...
Thanks in advance
found here Load jQuery with JavaScript using Promises
function loadScript(url) {
return new Promise(function(resolve reject) {
var script = document.createElement("script");
script.onload = resolve;
script.onerror = reject;
script.src = url;
document.getElementsByTagName("head")[0].appendChild(script);
});
}
function loadjQuery() {
if (window.jQuery) {
// already loaded and ready to go
return Promise.resolve();
} else {
return loadScript('https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js');
}
}
// Usage:
loadjQuery().then(function() {
// code here that uses jQuery
}, function() {
// error loading jQuery
});
This is quick, but I think it should work.
function downloadJSAtOnload() {
var element01 = document.createElement("script");
element01.src = "js/jquery.min.js";
document.body.appendChild(element01);
element01.onload = function() {
var element02 = document.createElement("script");
element02.src = "js/plugins.js";
document.body.appendChild(element02);
var element03 = document.createElement("script");
element03.src = "js/scripts.js";
document.body.appendChild(element03);
var element04 = document.createElement("script");
element04.src = "js/SmoothScroll.min.js";
document.body.appendChild(element04);
var element05 = document.createElement("script");
element05.src = "js/contact-form.js";
document.body.appendChild(element05);
}
}

Set response data from external JS script

I have this script
<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>
And I can't figure out how can I get response data from the script I'm trying to load.
Basically, this script contains a function that does something and then returns some value.
I know that in jQuery analog in would be just data argument in getScript function, but I only have native JS here.
What and where should I add to get response data in my script?
Assuming that your script contains a function declared in a global scope, you can simply include this script and then execute any function / access any member from this script:
After your script has been loaded and executed, you can work with it just like with a simple script which is a part of your current document.
Here is a demo which loads jQuery script from Google CDN and then outputs jQuery version (which is a part of jQuery library):
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);
}
console.log("typeof jQuery: " + typeof jQuery); // jQuery not loaded
loadJS("https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js", function() {
console.log("typeof jQuery: " + typeof jQuery + ", version = " + jQuery.fn.jquery); // jQuery has been loaded
});

can't run jQuery functions after appending jQuery from same file

I'm appending into my page multiple scripts including jQuery, jQuery migrate... all from same .js file
this is how it looks:
function appendScript(pathToScript, run) {
var head = document.getElementsByTagName("head")[0];
var js = document.createElement("script");
js.type = "text/javascript";
if(run == true){
js.onreadystatechange = function () {
if (this.readyState == 'complete') runFunctions();
}
js.onload = runFunctions;
}
js.src = pathToScript;
head.appendChild(js);
}
appendScript("http://code.jquery.com/jquery-latest.min.js");
appendScript("http://code.jquery.com/jquery-migrate-1.3.0.min.js", true);
function runFunctions(){
console.log('test') // all good till here
// here i have only jquery functions
$('#myDiv').addClass('test');
alert("this doesn't work");
....
}
My problem is that I can't run $(document).ready or any jQuery function, only javascript.
Tried with timeout too. Also I already have 1 x $(window).bind("load", function(){...} so I don't need 1 more
Since jQuery Migrate depends on jQuery, you need to wait until loading the next script.
Here is a working example (I also cleaned up some variables).
function appendScript(src, callback) {
var head = document.getElementsByTagName("head")[0];
var script = document.createElement("script");
script.type = "text/javascript";
if (callback) {
script.onload = callback;
}
script.src = src;
head.appendChild(script);
}
appendScript("https://code.jquery.com/jquery-latest.min.js", function() {
appendScript("https://code.jquery.com/jquery-migrate-1.3.0.min.js", function() {
document.body.innerHTML = 'Loaded jQuery version ' + jQuery.fn.jquery;
});
});
See working jsfiddle.

Js/jQuery include function not working in IE

i have following Code
function includeJSLib(lib, id, callback) {
if (!document.getElementById(id)) {
var s = document.createElement('script');
s.setAttribute('id', id);
s.setAttribute('async', 'false');
s.setAttribute('type', 'text/javascript');
s.src = lib;
document.getElementsByTagName('head')[0].appendChild(s);
s.onload = callback;
} else {
callback();
}
}
includeJSLib('https://code.jquery.com/jquery-1.11.3.min.js', 'jqueryInclude', function(){
jQuery(document).ready( function($) {
if ($('body').hasClass('class')) { do something }
});
});
it will load jQuery. In the callback function there is some custom code. the custom code works fine in Firefox and Chrome but not in IE.
The internet Explorer totally ignores the code snippets. Tested in IE 10/11.
Does anybody have a idea what the problem could be?
Thanks & Regards,
Noxx
p.s. The IE Debugger says nothing, it just jumps over the snippets. And i have to include jQuery this way (better dont ask :P)
For IE instead of onload use onreadystatechange:
function includeJSLib(lib, id, callback) {
if (!document.getElementById(id)) {
var s = document.createElement('script');
s.setAttribute('id', id);
s.setAttribute('async', 'false');
s.setAttribute('type', 'text/javascript');
s.src = lib;
document.getElementsByTagName('head')[0].appendChild(s);
var loaded = false;
s.onload = s.onreadystatechange = function() {
var readyState = this.readyState || 'complete';
if (!loaded && ('loaded' === readyState || 'complete' === readyState)) {
loaded = true;
// Handle memory leak in IE
s.onload = s.onreadystatechange = null;
s.parentNode.removeChild(s);
callback();
}
};
// s.onload = callback;
} else {
callback();
}
}
includeJSLib('https://code.jquery.com/jquery-1.11.3.min.js', 'jqueryInclude', function() {
jQuery(document).ready( function($) {
if ($('body').hasClass('class')) { do something }
});
});

Categories