Body onload in Javascript - javascript

I had written one JS in asp.net. I had called that from body onload, but the JS doesn't get called where I have put my debugger. What could be possible reasons for this? I'm developing website in dotnetnuke.
The JS I have written is syntactically and logically correct.
<script type="text/javascript">
var displayTime, speed, wait, banner1, banner2, link1, link2, bannerIndex, bannerLocations, bannerURLs;
function initVar() {
debugger;
displayTime = 10; // The amount of time each banner will be displayed in seconds.
speed = 5; // The speed at which the banners is moved (1 - 10, anything above 5 is not recommended).
wait = true;
banner1 = document.getElementById("banner1");
banner2 = document.getElementById("banner2");
//link1 = document.getElementById("link1");
//link2 = document.getElementById("link2");
//banner1 = document.getElementById("banner1");
//banner2 = document.getElementById("banner2");
banner1.style.left = 0;
banner2.style.left = 500;
bannerIndex = 1;
/* Important: In order for this script to work properly, please make sure that the banner graphic and the
URL associated with it have the same index in both, the bannerLocations and bannerURLs arrays.
Duplicate URLs are permitted. */
// Enter the location of the banner graphics in the array below.
//bannerLocations = new Array("internet-lg.gif","jupiterweb.gif","jupitermedia.gif");
bannerLocations = new Array("image00.jpg", "image01.jpg", "image02.jpg", "admin_ban.bmp");
// Enter the URL's to which the banners will link to in the array below.
bannerURLs = new Array("http://www.internet.com","http://www.jupiterweb.com","http://www.jupitermedia.com");
}
function moveBanner() {
//debugger;
if(!wait){
banner1.style.left = parseInt(banner1.style.left) - (speed * 5);
banner2.style.left = parseInt(banner2.style.left) - (speed * 5);
if(parseInt(banner1.style.left) <= -500){
banner1.style.left = 500;
bannerIndex = (bannerIndex < (bannerLocations.length - 1)) ? ++bannerIndex :0;
banner1.src = bannerLocations[bannerIndex];
//link1.href = bannerURLs[bannerIndex];
wait = true;
}
if(parseInt(banner2.style.left) <= -500){
banner2.style.left = 500;
bannerIndex = (bannerIndex < (bannerLocations.length - 1)) ? ++bannerIndex :0;
banner2.src = bannerLocations[bannerIndex];
//link2.href = bannerURLs[bannerIndex];
wait = true;
}
setTimeout("moveBanner()",100);
} else {
wait = false;
setTimeout("moveBanner()", displayTime * 1000);
}
}
</script>
REGISTRATION IN JS
<body onload="initVar(); moveBanner();">
</body>

I ran your code. Both methods executed without me having to make any modifications to the posted code. Is there possibly some other code that is overwriting the onload method?

The DotNetNuke best practice for binding to the "onload" property in JavaScript is to hook into JQuery's ready() method:
jQuery(document).ready( function() {
// put your code here
initVar();
moveBanner();
});
DotNetNuke 4.9.x and later ship with the jQuery JavaScript library included.

Have you edited DNN's Default.aspx? Otherwise, there isn't any way for you to have access to the body tag to add the onload attribute like you show.
How are you injecting this script? Are you using a Text/HTML module, are you using the Page Header Text setting for the page, are you adding it directly to the skin, have you written a custom module, or something else?
Instead of using the onload attribute on the body tag, I would suggest wiring up to that event in the script itself. If you're using any code to inject the script, you can ask DNN to register jQuery or a ScriptManager (for ASP.NET AJAX) so that you can use those libraries to wire the event up easily. If you can't guarantee that those are on the page, use the following:
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
addLoadEvent(function () {
initVar();
moveBanner();
});

I don't know much about asp.net but if you can put javascript code in your page, then you can try this alternative:
window.onload = function()
{
// any code here
}
This is the same as what you put in body tag.

The CSS left property takes a length, not an integer. You must have units for non-zero lengths. (Even when setting it using JavaScript!).

Related

Loading an image but onload/onerror not working as expected

I have a div
<div id='cards'>
Which I want to fill with images based on some logic. But only when images are first loaded into memory. Otherwise, through onerror I wanna fill in some text..
function pasteCard(card, to){
if (typeof(card) == 'string')
card = [card];
var image = [];
for (var i = 0; i < card.length; i++) {
image[i] = new Image();
image[i].src = '/sprites/open/' + card[i] + '.png';
image[i].onload = function() {
pasteImage(to, image[i]);
}
image[i].onerror = function() {
pasteText(to, card[i]);
}
// alert(card[i]) #1
}
function pasteImage(to, image) {
to.append(image);
}
function pasteText(to, text) {
// alert(card[i]) #2
to.append(text);
}
}
pasteCard(['ABC123', 'DEF456', 'GHI789'], $('#cards'));
But this isn't working.
Problem/weirdness: If only #2 alert is active it returns nothing. But strangely if #1 alert is also active it does kinda work... (but still doesn't load my images, and mostly fails too when other code is involved)
Question: Why is it not working without #1 alert (at least in that jsfiddle)
suggestions?: what should I do?
Onload and onerror events are fired (executed) outside the scope of your function so your variables will be undefined. In the event method you have access to this which is the image object. You can set a data attribute to each image and access that in your error event.
Here is an example:
http://jsfiddle.net/7CfEu/4/
The callbacks are not in the same scope as your image array is - therefor you need to declare a variable then will "connect the scopes" and use it inside the callbacks
also the i variable probably changes until the callback is fired - so by using it inside the callback you will get undefined behavior
for (var i = 0; i < card.length; i++) {
var current_card = card[i];
var current_image = new Image();
current_image.onload = function() {
pasteImage(to, current_image);
}
current_image.onerror = function() {
pasteText(to, current_card);
}
current_image.src = '/sprites/open/' + current_card + '.png';
image[i] = current_image;
}
Fiddle: http://jsfiddle.net/7CfEu/6/
(Also - closing the div tag is never a bad idea)
Just in case anyone ends up here for same reason I did.
Was going crazy because onload and onerror were not firing in the page I was building. Tried copy pasting
var myimage = new Image();
myimage.onload = function() { alert("Success"); };
myimage.onerror = function() { alert("Fail"); };
myimage.src = "mog.gif" //Doesn't exist.
Which was working within codepen and random otherwise blank pages.
Turns out the problem I was having was that I was doing AJAX requests earlier in the page. This involved authorization which in turn involved a call to
setRequestHeader();
This was resulting in a net::ERR_FILE_NOT_FOUND error instead of the expected GET mog.gif 404 (Not Found)
This seemed to prevent proper triggering of events.
Revert with
xhr.setRequestHeader("Authorization", "");

Can I "pre-load" an image with JS to be used as a CSS background-image?

Can images be preemptively loaded into the page with javascript so that they can be used at any time as a CSS background image without any request/upload delay?
If so, how?
You don't even need to use JS for this (with the downside of delaying the page load event). Include something like this:
<img src="/path/to/image.jpg.png.gif.bmp" style="display: none" />
This will trigger a request for the image, and add it to the local cache. When you set the CSS background-image property, the image will already be in the local cache, eliminating the delay of another request.
Alternatively, you can accomplish the same thing without delaying the page load by creating the images in JavaScript (this solution allows for multiple images):
function preload(list, callback, imageCallback) {
var at, len;
at = len = list.length;
for (var i = 0; i < len; i++ ) {
var img = new Image();
img.onload = function() {
if( imageCallback ) {
imageCallback.call(this, this, len-at, len);
}
if( !--at ) {
callback(list);
}
};
img.src = list[i];
list[i] = img;
}
}
You'd call this with:
var list = preload(["1.png","2.png","3.png" ... ], function complete(list) {
console.log('images all loaded!');
}, function loaded(image, index, listCount) {
console.log('image ' + index + ' of + 'listCount + 'is loaded');
});
(Thanks to #rlemon for the preload code)
I don't think that using an hidden img tag is the correct way, i'd rather use an "new Img(url)" and attaching to it an onload event where you can set the image as background-image to the element you want.
img = new Image();
img.onload = function(){
// set background-image
};
img.src = image_url;
be sure to put img.src after attaching onload, or you risk that the image is loaded before the event is attached.
Maybe a more complete base to build on:
function preload(list, callback, imageCallback, errorCallback) {
if (typeof(list) === "undefined"
|| list.length === 0) {
return;
}
var len = list.length;
var timers = {};
var checkLen0 = function() {
if (len === 0) {
if (typeof(callback) === "function") {
callback();
}
delete(timers)
}
}
var onload = function() {
clearTimeout(timers[img]);
if (typeof(imageCallback) === "function") {
imageCallback.call(img);
}
len--;
checkLen0();
}
var onerror = function() {
clearTimeout(timers[img]);
if (typeof(errorCallback) === "function") {
errorCallback.call(img);
}
len--;
checkLen0();
}
for (var i = 0; i < list.length; i++ ) {
var img = new Image();
img.onload = onload;
timers[img] = window.setTimeout(5000, onerror);
img.src = list[i];
}
}
While SomeKittens answer is valid, it'll delay the page load as commented by Jimmy. If you are using jquery, I'd go with something like this instead to keep your style, structure and logic separated:
<style>
.preload-img { display: none; }
</style>
...
<div class = "preload-img">/path/to/image.jpg.png.gif.bmp</div>
...
<script>
$(document).ready(function(){
$(".preload-img").each(function(){
preloadImage = new Image();
preloadImage.src = $(this).html();
});
});
</script>
Of course, from there on you can optimize/change it. The advantadge of this is that you can create the <div> dynamically with PHP and you can have all your javascript cached properly as a separated file.
There is an excellent framework for this job called Emerge.js
http://ilyabirman.net/projects/emerge/
Quote from project page:
Emerge.js is a framework for coordinated page loading. Normally, when a complex web page is loading, images appear in random order, causing unpleasant flashing. To replace it with nice and coordinated animations, programming is required. Emerge.js simplifies the task by removing the need to write any Javascript code. The framework uses a declarative approach, where you specify a desired behavior for each element and do not think about the implementation. Emerge.js uses jQuery.
Just as a caveat to SomeKittens' answer above, a particularly large background image should probably be added as a hidden background / via JavaScript after page load, as content images delay the firing of window.onload and may therefore create the perception of a slow loading page.
Given that it sounds like you're using dynamic content anyway, this may be an acceptable solution. It also allows you to do preloading programmatically as required, which may be better for maintenance.

Help me simplify this JS code

I'm a beginner in JS and want to know a way to simplify this code. There are 7 different divs with iframes, and also 7 different links. I have shown 1 div with iframe and 1 link. I have no idea where to start. Any help would be greatly appreciated.
NOTE: The code works to my needs, but I just need to simplify it (less js code in html, and more in js file).
JavaScript in .js file:
function show_visibility(){
for(var i = 0,e = arguments.length;i < e;i++){
var myDiv = document.getElementById(arguments[i]).style;
myDiv.display = "block";}
}
function hide_visibility(){
for(var i = 0,e = arguments.length;i < e;i++){
var myDiv = document.getElementById(arguments[i]).style;
myDiv.display = "none";}
}
function refFrame() {
for(var i = 0,e = arguments.length;i < e;i++){
document.getElementById(arguments[i]).src = document.getElementById(arguments[i]).src;
}
}
Div/iframe to be modified:
<div id="r1-box">
<iframe id="frame-box1" class="work" src="youtubelink" width="720" height="405" frameborder="0"></iframe>
</div>
Link to execute JS:
<a id="r1" href="javascript:refFrame('frame-box2','frame-box3','frame-box4','frame-box5','frame-box6','frame-box7');show_visibility('r1-box');hide_visibility('r2-box','r3-box', 'r4-box','r5-box','r6-box','r7-box');">
</a>
As a beginner you shouldn't start using jQuery until you understand Javascript more.
There are a few ways you could simplify this, the most immediate one would be to get the Javascript out of the link and into a Javascript file, or at the top of the page:
window.onload = function() {
document.getElementById('#r1').onclick = function() {
refFrame('frame-box2','frame-box3','frame-box4','frame-box5','frame-box6','frame-box7');
show_visibility('r1-box');
hide_visibility('r2-box','r3-box', 'r4-box','r5-box','r6-box','r7-box');
};
// more...
};
window.onload is an event which fires once the page has - you guessed it - finished loading. There are better ways of doing this, but this is about as basic as it gets. I'd advise you look at javascript domready?
After looking at your code a bit more, I realised all your seven links will do essentially the same thing. You can simply this by using a single function:
function refClick(id) {
var i = 7,
frames = [],
boxes = [];
while(i--) {
if(i != id) {
frames.push('frame-box' + i);
boxes.push('r' + i + '-box');
}
}
refFrame.apply(null, frames);
hide_visibility.apply(null, boxes);
show_visibility('r' + id + '-box');
}
What I'm doing here is looping through 7 times, and building an array of arguments for the refFrame and hide_visibility functions. The id variable tells the loop not to put in that id into the arrays.
Using the .apply method, I can apply an array as the arguments and call it normally.
For each of your links, you can apply the following function
document.getElementById('#r1').onclick = function() {
refClick(1);
};
document.getElementById('#r2').onclick = function() {
refClick(2);
};
//.....
You could start using jQuery.
http://jquery.com/

Return address of image or error if it doesn't exist

I know my problem is the fact that I can't check if the image is good until it has time to load. I'm trying to check width and return after it or the src changes (using onerror to set an src.) I'm always getting stuck with a race condition though, and it errors out long before the height and width or src change. When I reload, the image is cached and it works fine. I don't know how to avoid this. Here is my current code (also not working, it loops until Firefox complains.) I'm setting the return of this function to a variable. There are some writes in there I'm using to see how far it gets, and it stops in the while loop. I tried using getTimeout('tstit = chkload("thisisatest",tinypth);',250);, but that didn't work either. I wish I could force this to load in order...
function buildimg(tehname,myc,pth1,pth2,tinypth)
{
var myimg = pth1+tehname+"/"+tehname+"-"+myc+".jpg";
buildtest("thisisatest",myimg,tinypth);
var testimg = document.getElementById("thisisatest");
var tstit = chkload("thisisatest",tinypth);
while(tstit == false) {
document.write(tstit);
tstit = chkload("thisisatest",tinypth);
}
alert(testimg.src+'-'+testimg.width+'-'+testimg.height);
if((testimage.width > 20) && (testimage.height > 20)) {
return myimg;
}
else if(typeof pth2 == "undefined") {
myimg = "error";
return myimg;
}
else {
myimg = buildimg(tehname,myc,pth2);
return myimg;
}
document.write('No return error in buildimg.');
return "error";
}
/*Builds a hidden img tag for testing images*/
function buildtest(itsid,itssrc,tinypath) {
if(document.getElementById(itsid)) {
var imgobj = document.getElementById(itsid);
imgobj.remove();
}
document.write('<img id="'+itsid+'" style="display: none;" src="'+itssrc+'" onerror="swaponerr(\''+itsid+'\',\''+tinypath+'\')" />');
}
/*Swaps the image to a small picture, so we can detect if it worked*/
function swaponerr(tagid, tinypath) {
var theimg = document.getElementById(tagid);
theimg.onerror = '';
theimg.src = tinypath;
}
/*Recurses to return when the image is loaded*/
function chkload(loadid,tinychk) {
var tehobj = document.getElementById(loadid);
document.write(tehobj.width+'x'+tehobj.height+'x'+tehobj.src);
if((tehobj.naturalWidth > 20) && (tehobj.naturalHeight > 20)) {
return true;
}
if(tehobj.src == tinychk) {
return true;
}
return false;
}
I need to test for an image, and return error if it is non-existent. The code below works fine on my server:
/*Checks if the image at /tehname/tehname-c.jpg exists in either of the paths
outputs it's address if it does, and "error" if not.*/
function buildimg(tehname,index,pth1,pth2)
{
var myimg = pth1+tehname+"/"+tehname+"-"+index+".jpg";
$.ajax({
url:myimg,
type:'HEAD',
error: function()
{
myimg=pth2+tehname+"/"+tehname+"-"+index+".jpg";
$.ajax({
url:myimg,
type:'HEAD',
error: function()
{
myimg="error";
return;
},
});
return;
},
});
return myimg;
}
Unfortunately, I'm trying to do this on a messed up system my work uses. We do have jquery, but the system stores user files on a separate server from code, so ajax won't work. This will eventually be in a .js file, I hope.
Now I've got code starting with:
function buildimg(tehname,myc,pth1,pth2)
{
var myimg = pth1+tehname+"/"+tehname+"-"+myc+".jpg";
var tehimage = new Image();
tehimg.src = myimg;
I tried to have the function load the image, and check its width, but I always get 0, since I can't pre-load the images without knowing how many they are (and I don't want to have some outrageously high number of requests with most being errors.) For some reason (at least on Firefox 4, as that's what my goal is to get working first) tehimage.complete always returns false. I've tried using onerror and onload by a global variable, and a few other methods. I must admit though, I'm not very versed in Javascript, so my callbacks may not have worked.
Please help, I'm getting desperate!
Do you hold the 'power to execute php code' on that user files server? If so, check them in php and output to images.js in that server, than in your html, first load images.js, then your usual javascript.
By the way, jQuery had memory leaks in ajax for ears, don't know about 1.6, but 1.5 definately had those. if you wan't to use ajax to get data from server to javascript - use plain javascript: http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp
Edit: Definately worth checking out: http://fettig.net/weblog/2005/11/28/how-to-make-xmlhttprequest-connections-to-another-server-in-your-domain/
Since I'm getting no answers, I'm closing the question. What I ended up doing was a modification to make the image change class in the onload, have the image onerror delete it, and have the rest of the code run in the window onload. Unfortunately, this means the 404s aren't caught before it tries to load more images, so I'm forced to limit the max number of images that can be used (changeable in the function call,) and the images that aren't there just waste a little time.
See the final result here.

link element onload

Is there anyway to listen to the onload event for a <link> element?
F.ex:
var link = document.createElement('link');
link.rel = 'stylesheet';
link.href = 'styles.css';
link.onload = link.onreadystatechange = function(e) {
console.log(e);
};
This works for <script> elements, but not <link>. Is there another way?
I just need to know when the styles in the external stylesheet has applied to the DOM.
Update:
Would it be an idea to inject a hidden <iframe>, add the <link> to the head and listen for the window.onload event in the iframe? It should trigger when the css is loaded, but it might not guarantee that it's loaded in the top window...
Today, all modern browsers support the onload event on link tags. So I would guard hacks, such as creating an img element and setting the onerror:
if !('onload' in document.createElement('link')) {
imgTag = document.createElement(img);
imgTag.onerror = function() {};
imgTag.src = ...;
}
This should provide a workaround for FF-8 and earlier and old Safari & Chrome versions.
minor update:
As Michael pointed out, there are some browser exceptions for which we always want to apply the hack. In Coffeescript:
isSafari5: ->
!!navigator.userAgent.match(' Safari/') &&
!navigator.userAgent.match(' Chrom') &&
!!navigator.userAgent.match(' Version/5.')
# Webkit: 535.23 and above supports onload on link tags.
isWebkitNoOnloadSupport: ->
[supportedMajor, supportedMinor] = [535, 23]
if (match = navigator.userAgent.match(/\ AppleWebKit\/(\d+)\.(\d+)/))
match.shift()
[major, minor] = [+match[0], +match[1]]
major < supportedMajor || major == supportedMajor && minor < supportedMinor
This is kind of a hack, but if you can edit the CSS, you could add a special style (with no visible effect) that you can listen for using the technique in this post: http://www.west-wind.com/weblog/posts/478985.aspx
You would need an element in the page that has a class or an id that the CSS will affect. When your code detects that its style has changed, the CSS has been loaded.
A hack, as I said :)
The way I did it on Chrome (not tested on other browsers) is to load the CSS using an Image object and catching its onerror event. The thing is that browser does not know is this resource an image or not, so it will try fetching it anyway. However, since it is not an actual image it will trigger onerror handlers.
var css = new Image();
css.onerror = function() {
// method body
}
// Set the url of the CSS. In link case, link.href
// This will make the browser try to fetch the resource.
css.src = url_of_the_css;
Note that if the resource has already been fetched, this fetch request will hit the cache.
E.g. Android browser doesn't support "onload" / "onreadystatechange" events for element: http://pieisgood.org/test/script-link-events/
But it returns:
"onload" in link === true
So, my solution is to detect Android browser from userAgent and then wait for some special css rule in your stylesheet (e.g., reset for "body" margins).
If it's not Android browser and it supports "onload" event- we will use it:
var userAgent = navigator.userAgent,
iChromeBrowser = /CriOS|Chrome/.test(userAgent),
isAndroidBrowser = /Mozilla\/5.0/.test(userAgent) && /Android/.test(userAgent) && /AppleWebKit/.test(userAgent) && !iChromeBrowser;
addCssLink('PATH/NAME.css', function(){
console.log('css is loaded');
});
function addCssLink(href, onload) {
var css = document.createElement("link");
css.setAttribute("rel", "stylesheet");
css.setAttribute("type", "text/css");
css.setAttribute("href", href);
document.head.appendChild(css);
if (onload) {
if (isAndroidBrowser || !("onload" in css)) {
waitForCss({
success: onload
});
} else {
css.onload = onload;
}
}
}
// We will check for css reset for "body" element- if success-> than css is loaded
function waitForCss(params) {
var maxWaitTime = 1000,
stepTime = 50,
alreadyWaitedTime = 0;
function nextStep() {
var startTime = +new Date(),
endTime;
setTimeout(function () {
endTime = +new Date();
alreadyWaitedTime += (endTime - startTime);
if (alreadyWaitedTime >= maxWaitTime) {
params.fail && params.fail();
} else {
// check for style- if no- revoke timer
if (window.getComputedStyle(document.body).marginTop === '0px') {
params.success();
} else {
nextStep();
}
}
}, stepTime);
}
nextStep();
}
Demo: http://codepen.io/malyw/pen/AuCtH
Since you didn't like my hack :) I looked around for some other way and found one by brothercake.
Basically, what is suggested is to get the CSS using AJAX to make the browser cache it and then treat the link load as instantaneous, since the CSS is cached. This will probably not work every single time (since some browsers may have cache turned off, for example), but almost always.
Another way to do this is to check how many style sheets are loaded. For instance:
With "css_filename" the url or filename of the css file, and "callback" a callback function when the css is loaded:
var style_sheets_count=document.styleSheets.length;
var css = document.createElement('link');
css.setAttribute('rel', 'stylesheet');
css.setAttribute('type', 'text/css');
css.setAttribute('href', css_filename);
document.getElementsByTagName('head').item(0).appendChild(css);
include_javascript_wait_for_css(style_sheets_count, callback, new Date().getTime());
function include_javascript_wait_for_css(style_sheets_count, callback, starttime)
/* Wait some time for a style sheet to load. If the time expires or we succeed
* in loading it, call a callback function.
* Enter: style_sheet_count: the original number of style sheets in the
* document. If this changes, we think we finished
* loading the style sheet.
* callback: a function to call when we finish loading.
* starttime: epoch when we started. Used for a timeout. 12/7/11-DWM */
{
var timeout = 10000; // 10 seconds
if (document.styleSheets.length!=style_sheets_count || (new Date().getTime())-starttime>timeout)
callback();
else
window.setTimeout(function(){include_javascript_wait_for_css(style_sheets_count, callback, starttime)}, 50);
}
This trick is borrowed from the xLazyLoader jQuery plugin:
var count = 0;
(function(){
try {
link.sheet.cssRules;
} catch (e) {
if(count++ < 100)
cssTimeout = setTimeout(arguments.callee, 20);
else
console.log('load failed (FF)');
return;
};
if(link.sheet.cssRules && link.sheet.cssRules.length == 0) // fail in chrome?
console.log('load failed (Webkit)');
else
console.log('loaded');
})();
Tested and working locally in FF (3.6.3) and Chrome (linux - 6.0.408.1 dev)
Demo here (note that this won't work for cross-site css loading, as is done in the demo, under FF)
You either need a specific element which style you know, or if you control the CSS file, you can insert a dummy element for this purpose. This code will exactly make your callback run when the css file's content is applied to the DOM.
// dummy element in the html
<div id="cssloaded"></div>
// dummy element in the css
#cssloaded { height:1px; }
// event handler function
function cssOnload(id, callback) {
setTimeout(function listener(){
var el = document.getElementById(id),
comp = el.currentStyle || getComputedStyle(el, null);
if ( comp.height === "1px" )
callback();
else
setTimeout(listener, 50);
}, 50)
}
// attach an onload handler
cssOnload("cssloaded", function(){
alert("ok");
});
If you use this code in the bottom of the document, you can move the el and comp variables outside of the timer in order to get the element once. But if you want to attach the handler somewhere up in the document (like the head), you should leave the code as is.
Note: tested on FF 3+, IE 5.5+, Chrome
The xLazyLoader plugin fails since the cssRules properties are hidden for stylesheets that belong to other domains (breaks the same origin policy). So what you have to do is compare the ownerNode and owningElements.
Here is a thorough explanation of what todo:
http://yearofmoo.com/2011/03/cross-browser-stylesheet-preloading/
// this work in IE 10, 11 and Safari/Chrome/Firefox/Edge
// if you want to use Promise in an non-es6 browser, add an ES6 poly-fill (or rewrite to use a callback)
let fetchStyle = function(url) {
return new Promise((resolve, reject) => {
let link = document.createElement('link');
link.type = 'text/css';
link.rel = 'stylesheet';
link.onload = resolve;
link.href = url;
let headScript = document.querySelector('script');
headScript.parentNode.insertBefore(link, headScript);
});
};
This is a cross-browser solution
// Your css loader
var d = document,
css = d.head.appendChild(d.createElement('link'))
css.rel = 'stylesheet';
css.type = 'text/css';
css.href = "https://unpkg.com/tachyons#4.10.0/css/tachyons.css"
// Add this
if (typeof s.onload != 'undefined') s.onload = myFun;
} else {
var img = d.createElement("img");
img.onerror = function() {
myFun();
d.body.removeChild(img);
}
d.body.appendChild(img);
img.src = src;
}
function myFun() {
/* ..... PUT YOUR CODE HERE ..... */
}
The answer is based on this link that say:
What happens behind the scenes is that the browser tries to load the
CSS in the img element and, because a stylesheet is not a type of
image, the img element throws the onerror event and executes our
function. Thankfully, browsers load the entire CSS file before
determining its not an image and firing the onerror event.
In modern browsers you can do css.onload and add that code as a fallback to cover old browsers back to 2011 when only Opera and Internet Explorer supported the onload event and onreadystatechange respectively.
Note: I have answered here too and it is my duplicate and deserves to be punished for my honesteness :P

Categories

Resources