Js judges the specific implementation of CSS file loading completion _ javascript skills

Source: Internet
Author: User
In most cases, we do not need to determine whether the css file is successfully loaded. However, this function is still required for some time, today, I 've sorted out how to determine whether a CSS file is loaded in a variety of browsers. I 'd like to share with you how to determine whether the CSS file has been loaded. The practices of various browsers vary greatly, this time I want to say that IE has done a good job. We can use the onload method to handle the processing after CSS loading is completed:

The Code is as follows:


// Code excerpt to seajs
Function styleOnload (node, callback ){
// IE6-9 and Opera
If (node. attachEvent ){
Node. attachEvent ('onload', callback );
// NOTICE:
// 1. "onload" will be fired in IE6-9 when the file is 404, but in
// This situation, Opera does nothing, so fallback to timeout.
// 2. "onerror" doesn't fire in any browsers!
}
}

Whether the specified Rules attribute exists to determine whether the load is complete. In addition, the setTimeout interval event polling is required:

The Code is as follows:


// Code excerpt to seajs
Function poll (node, callback ){
If (callback. isCalled ){
Return;
}
Var isLoaded = false;
If (/webkit/I. test (navigator. userAgent) {// webkit
If (node ['sheet ']) {
IsLoaded = true;
}
}
// For Firefox
Else if (node ['sheet ']) {
Try {
If (node+'sheet'}.css Rules ){
IsLoaded = true;
}
} Catch (ex ){
// NS_ERROR_DOM_SECURITY_ERR
If (ex. code = 1000 ){
IsLoaded = true;
}
}
}
If (isLoaded ){
// Give time to render.
SetTimeout (function (){
Callback ();
}, 1 );
}
Else {
SetTimeout (function (){
Poll (node, callback );
}, 1 );
}
}

SetTimeout (function (){
Poll (node, callback );
}, 0 );

The complete processing provided by SeaJS is as follows:

The Code is as follows:


Function styleOnload (node, callback ){
// IE6-9 and Opera
If (node. attachEvent ){
Node. attachEvent ('onload', callback );
// NOTICE:
// 1. "onload" will be fired in IE6-9 when the file is 404, but in
// This situation, Opera does nothing, so fallback to timeout.
// 2. "onerror" doesn't fire in any browsers!
}
// Polling for Firefox, Chrome, Safari
Else {
SetTimeout (function (){
Poll (node, callback );
}, 0); // for cache
}
}
Function poll (node, callback ){
If (callback. isCalled ){
Return;
}
Var isLoaded = false;
If (/webkit/I. test (navigator. userAgent) {// webkit
If (node ['sheet ']) {
IsLoaded = true;
}
}
// For Firefox
Else if (node ['sheet ']) {
Try {
If (node+'sheet'}.css Rules ){
IsLoaded = true;
}
} Catch (ex ){
// NS_ERROR_DOM_SECURITY_ERR
If (ex. code = 1000 ){
IsLoaded = true;
}
}
}
If (isLoaded ){
// Give time to render.
SetTimeout (function (){
Callback ();
}, 1 );
}
Else {
SetTimeout (function (){
Poll (node, callback );
}, 1 );
}
}
// My dynamically create LINK functions
Function createLink (cssURL, lnkId, charset, media ){
Var head = document. getElementsByTagName ('head') [0],
LinkTag = null;

If (! CssURL ){
Return false;
}

LinkTag = document. createElement ('link ');
LinkTag. setAttribute ('id', (lnkId | 'dynamic-style '));
LinkTag. setAttribute ('rel ', 'stylesheet ');
LinkTag. setAttribute ('charset', (charset | 'utf-8 '));
LinkTag. setAttribute ('media', (media | 'all '));
LinkTag. setAttribute ('type', 'text/css ');
LinkTag. href = cssURL;

Head. appendChild (linkTag );
}
Function loadcss (){
Var styleNode = createLink ('/wp-content/themes/BlueNight/style.css ');

StyleOnload (styleNode, function (){
Alert ("loaded ");
});
}


When I saw the seajs code, I immediately remembered another solution I saw for Diego Perini:

The Code is as follows:


/*
* Copyright (C) 2010 Diego Perini
* All rights reserved.
*
* Cssready. js-CSS loaded/ready state notification
*
* Author: Diego Perini
* Version: 0.1
* Created: 20100616
* Release: 20101104
*
* License:
* Http://www.jb51.net * Download:
* Http://javascript.nwbox.com/cssready/cssready.js
*/
Function cssReady (fn, link ){
Var d = document,
T = d. createStyleSheet,
R = t? 'Rules': 'cssrules ',
S = t? 'Stylesheet ': 'sheet ',
L = d. getElementsByTagName ('link ');
// Passed link or last link node
Link | (link = l [l. length-1]);
Function check (){
Try {
Return link & link [s] & link [s] [r] & link [s] [r] [0];
} Catch (e ){
Return false;
}
}
(Function poll (){
Check () & setTimeout (fn, 0) | setTimeout (poll, 100 );
})();
}

In fact, if you have read the code used to judge the domready event of jQuery, the principle is similar. The setTimeout round-robin method is also used to determine whether the DOM node has been loaded.
In addition, Fackbook includes a fixed style in the dynamically created CSS style, for example, # loadcssdom. loadcssdom is a 1px style with a height. Then dynamically create a DOM object and add the loadcssdom style. Then, setTimeout polls whether loadcssdo has a 1px height. For the solution of this method, you can go to "CSSP: Loading CSS with Javascript-and getting an onload callback."
In his blog, Stoyan, author of JavaScript Patterns, explained in detail "When is a stylesheet really loaded?".
After reading this, you may lament that it is not so easy to sweat and determine whether the CSS has been loaded! In fact, I am here to introduce myself, because in development, in addition to dynamic loading of CSS, we also need to dynamically load JavaScript and HTML operations. When I have time, I will also write content about dynamic loading of JavaScript, but before that, I suggest you look at these:
"Ensure-Ensure JavaScripts/HTML/CSS are loaded on-demand when needed". This library specifically handles dynamic loading of HTML, CSS, and JavaScript. As described by the author:
Ensure is a tiny JavaScript library that provides a handy function ensure which allows you to load JavaScript, HTML, CSS on-demand, and then execute your code. ensure www.jb51.net ensures that the relevant JavaScript and HTML snippets are already in the browser DOM before executing your code that uses them.
Tell CSS that JavaScript is available ASAP
After reading this, you may not be confused: When you're styling parts of a web page that will look and work differently depending on whether JavaScript is available or not.
Well, I have said so much this time. I hope it will be helpful for everyone's development and learning!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.