This code leads to :Uncaught error : check is not defined.Can some one help regarding this code snippet. Please find below code
The check() is define in external .js file
Method in script tag ...
<script>
loadScriptfinal("/js/VendorPaymentInfo/"+coreId+".js", function() {
check();
});
function loadJS(file,callback) {
var jsElm = document.createElement("script");
jsElm.type = "application/javascript";
jsElm.src = file;
jsElm.onload = function() {
callback();
}
// finally insert the element to the body element in order to load the script
document.body.appendChild(jsElm);
}
</script>
You can watch till the external file is loaded and then call loadScriptfinal function.
var timer = null;
var timer = setInterval(()=>{
if (window.check && window.check.constructor === Function) {
clearInterval(timer);
loadScriptfinal("/js/VendorPaymentInfo/"+coreId+".js", function() {
check();
});
}
},100)
Related
I am making javascript for Page loader.
This is part of it.
$('img').each(function () {
var src = $(this).attr('src');
$('<img>').attr('src', src).on("load", function () {
alert("Loaded one of thme");
});
});
I can get callback from this, img files are OK.
But how to get callback of CSS files and JS files, especially font files?
regard.
/////////////////// add My resolve at 5/14
I resolved like this. Is this for just my case.
In HTML, Put link tags for fonts. Any where OK.
<link as="font" href="/fonts/font01.woff">
<link as="font" href="/fonts/font02.woff">
<img src="/img/img01.jpg">
<img src="/img/img02.jpg">
Next JS.
var fonts_length = $('link[as="font"]').length;
var resouce_num = $('img').length + fonts_length;
$('img').each(function () {
var src = $(this).attr('src');
$('<img>').attr('src', src).on("load", function () {
loadStatus++;
});
});
$('link[as="font"]').each(function () {
var href = $(this).attr('href');
$(document).load(href, function () {
loadStatus++;
});
});
And Compare loadStatus(loaded files count) and resouce_num(need load files count).
Is this correct using? I do not know, but working well, should be alright.
how do you think? If you have better way or found my mistake, tell me please.
And B--rian! please fix my english too!!
/////////////////// add Other nice way at 5/14
I found other one.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link#Stylesheet_load_events
<script>
var myStylesheet = document.querySelector('#my-stylesheet');
myStylesheet.onload = function() {
// Do something interesting; the sheet has been loaded
}
myStylesheet.onerror = function() {
console.log("An error occurred loading the stylesheet!");
}
</script>
<link rel="stylesheet" href="mystylesheet.css" id="my-stylesheet">
important Note:
Note: The load event fires once the stylesheet and all of its imported
content has been loaded and parsed, and immediately before the styles
start being applied to the content.
This way is much simple I thought.
But today I am so tired...later I will try.
/////////////////// add My trying at 5/15
I tried above one.But "onload" function is not working well.
It does not send callback after loaded... Chrome has problem? or My mistake?
Or this way is not nice for Page loader, I thought.
Cos, Even If that is working well, Can not check each loading of font files.
I think, Page loader should tell a temporary percentage of progress with a progress bar or something.
So, Now I am back to my sample script.
CSS files:
// create a nodeElement
var node = document.createElement('link');
node.rel = 'stylesheet';
node.href = url;
document.head.insertBefore(node, document.head.firstChild);
// try to set load callback
node.onload = function () {
CSSDone('onload listener');
// do your callback
}
if (node.addEventListener) {
node.addEventListener('load', function() {
CSSDone("DOM's load event");
// do your callback
}, false);
}
node.onreadystatechange = function() {
var state = node.readyState;
if (state === 'loaded' || state === 'complete') {
node.onreadystatechange = null;
CSSDone("onreadystatechange");
// do your callback
}
};
var cssnum = document.styleSheets.length;
var ti = setInterval(function() {
if (document.styleSheets.length > cssnum) {
CSSDone('listening to styleSheets.length change');
// do your callback
clearInterval(ti);
}
}, 10);
you can see this link for reference
JS files:
// create a nodeElement
var body = document.getElementsByTagName('body')[0];
var node = document.createElement('script');
node.setAttribute('type', 'text/javascript');
node.setAttribute('src', url);
body.appendChild(node);
// try to set load callback
if(node.onload){
node.onload = function() {
// do your callback
}
}else{
// for some not support onload
node.onreadystatechange = function() {
// do your callback
}
}
font files:
document.fonts.onloadingdone = function() {
// do your callback
}
how to check font files loaded can refer this link
emm,I am New contributor.if there are some wrong can reply me.thanks
If you are trying to print out the contents of a .css or .html file, you can do this with php:
<?php
$myfile = fopen("your_file", "r") or die("Unable to open file!");
echo fread($myfile,filesize("your_file"));
fclose($myfile);
?>
I have a local JS file that needs to be called using a script object. However, I am not able to get the functions to run. Here's the code snippet.
<script type="text/javascript">
var x = document.createElement("SCRIPT");
x.type = "text/javascript";
x.src = "file:///C:/scripts/localscript.js";
//one of the functions is loadData();
loadData(); //I'm getting reference error, loadData is not defined.
</script>
Thank you,
You need to create a script element and insert it in DOM (mostly under head) to load the script. When that script is loaded by the browser, whatever you return from that script will be available.
Consider sampleScript.js with below code
(function(window){
'use strict';
window.app = {
sayHi: function() {
console.log('Hey there !');
}
};
})(this);
To load this script, I do
<script>
var node = document.createElement('script');
node.src = 'sampleScript.js';
node.addEventListener('load', onScriptLoad, false);
node.async = true;
document.head.appendChild(node);
function onScriptLoad(evt) {
console.log('Script loaded.');
console.log('app.sayHi ---> ');
app && app.sayHi();
}
</script>
Taking cues, you can fit to your need. Hope this helps.
Use the onload event:
x.onload = function() { window.loadData(); }
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.
});
I have a array where i have specified the files i need to load in javascript before calling specific script. Lets call those particular lines of code as myscript.
I did as follows
var fileNamesArray = new Array();
fileNamesArray.push("abc.js");
fileNamesArray.push("pqr.js");
fileNamesArray.push("xyz.js");
fileNamesArray.push("klm.js");
var totalFiles = jQuery(fileNamesArray).length;
var tempCount = 0;
jQuery.each(fileNamesArray, function(key, value) {
jQuery.getScript(value, function() {
tempCount++;
});
});
to check whether all files are being loaded or not, i done following thing but doesn't seems to be effective
var refreshIntervalId = setInterval(function() {
if (tempCount == totalFiles) {
clearInterval(refreshIntervalId);
return;
}
}, 10);
i have implemented these in object oriented javascript as follows
function Loader() {
this.jQuery = null;
// check for specifically jQuery 1.8.2+, if not, load it
if (jQuery == undefined) {
jQuery.getScript(
"/Common/javascript/jquery/map/javascript/jquery-1.8.2.js",
function() {
this.jQuery = jQuery.noConflict();
});
} else {
var jQueryVersion = $.fn.jquery;
jQueryVersion = parseInt(jQueryVersion.split('.').join(""));
if (182 > jQueryVersion) {
jQuery.getScript(
"/Common/javascript/jquery/map/javascript/jquery-1.8.2.js",
function() {
this.jQuery = jQuery.noConflict();
});
}
}
}
Loader.prototype.LoadAllFile = function() {
//here i am loading all files
}
Loader.prototype.bindMap = function(options) {
this.LoadAllFile();
//execute the script after loading the files... which we called as myscript
}
i am loading more than 12-14 js files via ajax.
if you observe Loader.prototype.bindMap, i am loading all the files first and then executing the script.
But it seems that myscript the script start executing before all files being loaded.
what are the better ways to execute the script only after all js files are loaded.
Take a look at jQuery's .load() http://api.jquery.com/load-event/
$('script').load(function () { });
Based on the documentation on Jquery.getScript , it is a shorthand for Jquery.ajax. By default this in async call. You might want to change it to do a synchronous call.
To set this property, you can refer to this
So instead of doing a setInterval, you can just loop in your array and do a Jquery.getScript.
I have made a namespaces framework for javascript. I am loading some plugins (.js files) which are dynamically added to the HTML.
I am going to try to simplify the code.
This function is used to dinamically load a JS. The callback function is called after .js file has been loaded. Consider that the following code has already been run.
MYNAMESPACE.plugins = ["plugin1", "plugin2"];
MYNAMESPACE.getJS = {
get: function (url, callback) {
var script = document.createElement("script");
var head = document.getElementsByTagName('head')[0];
script.type = "text/javascript";
script.src = url;
head.insertBefore(script, head.firstChild)
script.onload = callback;
script.onreadystate = callback;
return script;
}
};
I have a init function that loads the plugins contained in MYNAMESPACE.plugins as follows:
MYNAMESPACE.init = function (callback) {
for (index in MYNAMESPACE.plugins) {
plugin = MYNAMESPACE.plugins[index];
MYNAMESPACE.getJS.get(plugin + '.js', function ()
{
// This callback is executed when the js file is loaded
});
}
// Here I want to execute callback function, but after all the callbacks in the for loop have been executed. Something like: if (alljsloaded) callback();
}
In my HTML I have the following script tag:
<html>
<head>
<script type="text/javascript">
$(document).ready(function () {
MYNAMESPACE.init();
// The following line is not executed correctlybecause init finished before the scripts are loaded and the functionOnPlugin1 is undefined.
MYNAMESPACE.functionOnPlugin1();
});
</script>
</head>
<body>
</body>
</html>
And I want to change it for something like this:
<html>
<head>
<script type="text/javascript">
$(document).ready(function () {
MYNAMESPACE.init(function() { MYNAMESPACE.functionOnPlugin1(); });
});
</script>
</head>
<body>
</body>
</html>
But I don't know how to modify the function MYNAMESPACE.init() so it executes the callback after ALL the plugin scripts are loaded.
Any ideas? Maybe using closures.
Use for(;;) to loop through an array, not for(.. in ..).
Create a counter in the function, increment it every time that a script has loaded. When it has reached the number of scripts, invoke the callback function.
Code:
MYNAMESPACE.init = function (callback) {
var allPluginsLength = MYNAMESPACE.plugins.length;
var loadedCount = 0;
if (allPluginsLength === 0) callback(); // No plugins, invoke callback.
else for (var index=0; index<allPluginsLength; i++) {
plugin = MYNAMESPACE.plugins[index];
MYNAMESPACE.getJS.get(plugin + '.js', function () {
// This callback is executed when the js file is loaded
if (++loadedCount == allPluginsLength) {
callback();
}
});
}
}
Also, change your getJS.get method. Currently, callback always executes when a state changes, which is not desirable. To prevent the callback from being executed twice, the following can be used:
script.onload = function() {
callback && callback();
callback = false;
};
// onreadystatechange instead of onreadystate, btw.
script.onreadystatechange = function() {
if (this.readyState == 'complete') {
callback && callback();
callback = false;
}
};
callback && callback() is used, to ensure that a callback exists. If it does, it's then invoked.
After invoking the callback, it's immediately removed (callback = null).
This is necessary, because the onload and onreadystatechange events can fire when the script has loaded. Without my suggested code, the callback will be called multiple times for a single script.
Some changes like this should work:
MYNAMESPACE.init = function (callback) {
var remaining = MYNAMESPACE.plugins.length;
for (index in MYNAMESPACE.plugins) {
plugin = MYNAMESPACE.plugins[index];
MYNAMESPACE.getJS.get(plugin + '.js', function ()
{
// This callback is executed when the js file is loaded
remaining = remaining - 1;
if (remaining === 0)
{
callback();
}
});
}
}