I want to dynamically insert some HTML content and some CSS urls through JS.
我想通过JS动态插入一些HTML内容和一些CSS网址。
I have 3+ CSS files. I want them to be downloaded before my content is inserted on the page.
我有3个以上的CSS文件。我希望在我的内容插入页面之前下载它们。
Is there a way to find out whether the above-mentioned files have been downloaded?
有没有办法找出上面提到的文件是否已下载?
This is how it should work:
这是它应该如何工作:
- Download css files;
- Show HTML after all the css files have been downloaded;
- Start loading JS files after inserting the the HTML;
- Trigger callback after all the JS files have been loaded;
下载css文件;
下载完所有css文件后显示HTML;
插入HTML后开始加载JS文件;
加载完所有JS文件后触发回调;
10 个解决方案
#1
3
You could use YepNope.js, YepNope allows you to build asynchronous conditional tests to see whether resources have loaded. Once your tests have passed you can tell it to inject new CSS or JS files.
您可以使用YepNope.js,YepNope允许您构建异步条件测试以查看资源是否已加载。一旦你的测试通过,你可以告诉它注入新的CSS或JS文件。
Example below has been taken from the YepNope.js site.
以下示例取自YepNope.js站点。
yepnope.injectCss( stylesheetSource [, callback ] [, elemAttributes ] [, timeout ]);
// Example
yepnope.injectCss("print.css", function () {
console.log("css injected!");
}, {
media: "print"
}, 5000);
You can even make YepNope load the initial CSS files first and then once they have completed loading YepNope can trigger a callback to do additional tasks, such as loading more JS or CSS files.
您甚至可以让YepNope首先加载初始CSS文件,然后一旦完成加载,YepNope就可以触发回调来执行其他任务,例如加载更多JS或CSS文件。
#2
3
Source: https://*.com/a/3794242/1292652
Retreiving CSS text using AJAX
Instead of using messy workarounds to determine of the CSS has loaded, you can use AJAX function to create a dynamic CSS URL and fetch the it as plain text.
您可以使用AJAX函数创建动态CSS URL并将其作为纯文本格式获取,而不是使用凌乱的变通方法来确定已加载的CSS。
Inserting the CSS
After fetching the raw text, you can use this function to insert the CSS into a style
tag and add a callback:
获取原始文本后,您可以使用此函数将CSS插入样式标记并添加回调:
function loadCss(cssText, callback) {
var style = document.createElement('style');
style.type='text/css';
if(callBack != undefined){
style.onload = function() {
callback();
};
}
style.innerHTML = cssText;
head.appendChild(style);
}
Using it
And now you can use this as:
现在你可以用它作为:
loadCss(ajaxResponseText, function(){
console.log("CSS loaded, you can show the dialog now :)");
})
Allowing cross-domain AJAX
In your comment, you mentioned you had to load jQuery
and jQueryUI
which I'm guessing wil de on a different domain.
在你的评论中,你提到你必须加载jQuery和jQueryUI,我猜他们会在不同的域上。
To get around the AJAX cross-domain restriction, check out this link or this one or this library
要解决AJAX跨域限制,请查看此链接或此库或此库
#3
1
<html>
<head>
<!--
Put your styles here. Make sure the *last* CSS file has the following:
body { display: block !important }
This will allow the stylesheets to load while the body is hidden.
When the last stylesheet is loaded, the body will be visible.
-->
</head>
<body style="display: none">
<!-- Lots of HTML here -->
<!--
Put your script tags here.
In the first script, I recommend binding to the window.load event...
which will be fired once all your scripts are done loading.
-->
</body>
</html>
#4
0
I think this is somewhat along the lines of what you wanted:
我认为这有点像你想要的:
<html>
<head>
<!-- CSS Stuff goes here -->
<!-- JS Stuff come right after -->
</head>
<body>
<!-- HTML Stuff comes withing Body -->
</body>
</html>
This will cause:-
这将导致: -
- All the CSS files to download in parallel;
- Then the HTML stuff gets parsed and displayed;
- The browser gets all the JS;
- The JS is tun and it does whatever inserting it wants;
所有CSS文件并行下载;
然后解析并显示HTML内容;
浏览器获取所有JS;
JS是tun,它可以执行任何插入操作;
Your question is a bit confusing, can you clarify it? I didn't understand why you'd require to have such an order, can you give the big picture? JS is meant to be a fire-and-forget language, it will be awkard to see if everything's downloaded. Did this make sense to you and/or help you?
你的问题有点令人困惑,你能澄清一下吗?我不明白你为什么要这么订单,你能说出全局吗? JS本来就是一种昙花一现的语言,看看是否所有内容都下载都很麻烦。这对你有意义和/或帮助你吗?
#5
0
I know it is not a pretty solution, but you can fetch the CSS files using AJAX and add their content to a <style>
, instead of inserting a <link>
to the DOM. Using AJAX, you can know for sure when the CSS is completely downloaded and add the whole thing into the page under your terms.
我知道这不是一个漂亮的解决方案,但您可以使用AJAX获取CSS文件并将其内容添加到
#6
0
Source: https://*.com/a/8122005/1292652
I don't recommend this for the same reason why you shouldn't use a while
loop to implement sleep()
, but if you must, you can try it.
我不推荐这个,因为你不应该使用while循环来实现sleep(),但如果你必须,你可以试试。
In the linked answer, a reference style was added. For example: #ensure-cssload-8473649 { display: none }
. But since you're downloading files not in your control, you'll have to select a few styles from the sheet for detection.
在链接的答案中,添加了参考样式。例如:#ensure-cssload-8473649 {display:none}。但是,由于您下载的文件不在您的控件中,因此您必须从工作表中选择一些样式进行检测。
The cssLoad()
function is:
cssLoad()函数是:
var onCssLoad = function (options, callback) {
var body = $("body");
var div = document.createElement(constants.TAG_DIV);
for (var key in options) {
if (options.hasOwnProperty(key)) {
if (key.toLowerCase() === "css") {
continue;
}
div[key] = options[key];
}
}
var css = options.css;
if (css) {
body.appendChild(div);
var handle = -1;
handle = window.setInterval(function () {
var match = true;
for (var key in css) {
if (css.hasOwnProperty(key)) {
match = match && utils.getStyle(div, key) === css[key];
}
}
if (match === true) {
window.clearTimeout(handle);
body.removeChild(div);
callback();
}
}, 100);
}
}
You can use it as:
您可以将其用作:
onCssLoad({
"id": <insert element CSS applies to>,
css: <insert sample CSS styles>
}, function () {
console.log("CSS loaded, you can show the dialog now :)");
});
#7
0
Why don't you add an element on page and check some style that it should have with some js. If it has that style then that stylesheet is probably load.
为什么不在页面上添加元素并检查一些js应该具有的样式。如果它具有该样式,则该样式表可能已加载。
Like this:
if (document.getElementById("csspage-3-box").style.color === "#somethingUnique") {
//it is loaded
}
You could append a few hidden divs with IDs unique to each style sheet. If they have any styles at all then you know that the sheet you want is loaded. This operation is cheap. It does add some non-semantic div elements though. That being said, I feel like everyone has at least one non-semantic element in their DOM.
您可以附加一些隐藏的div,其中每个样式表都有唯一的ID。如果他们有任何样式,那么你知道你想要的表被加载。这个操作很便宜。它确实添加了一些非语义div元素。话虽这么说,我觉得每个人的DOM中至少有一个非语义元素。
Just a suggestion, but 3 css files isn't that many. Other easy solutions include the following:
只是一个建议,但3 css文件并不是那么多。其他简单的解决方案包括:
A) You could just cat and minify them and deliver them all at once.
B) Throw them onto a CDN (like aws s3 + cloudfront), which is super cheap and they will get loaded in parallel.
C) Just load them in as normal. You could also put them on a sub domain.
A)您可以将它们缩小并缩小它们并立即将它们全部送出。 B)将它们扔到CDN(如aws s3 + cloudfront)上,这是非常便宜的,它们将并行加载。 C)正常加载它们。您也可以将它们放在子域上。
Now that aside if I were you I'd divide my CSS down into a bunch of files. 3 is too few files. I'd separate out grid and every element type. Then re-assemble them on a per page basis (or page group). This allows you to include each individual piece as you need.
现在除了我是你,我将我的CSS分成一堆文件。 3文件太少了。我将网格和每种元素类型分开。然后在每页(或页面组)的基础上重新组装它们。这允许您根据需要包含每个单独的部分。
After all that it is fairly easily to append a link tag (as long as you can easily get a path to it). I recommend using the link instead of the style tag because if you do go the CDN route or subdomain route you will have issues with cross-domain issues if trying to grab the content of the css file with some xhr.
毕竟,附加链接标记相当容易(只要您可以轻松获得它的路径)。我建议使用链接而不是样式标记,因为如果你去CDN路由或子域路由,如果尝试使用某些xhr获取css文件的内容,则会出现跨域问题。
#8
0
In building the apps that our team develops there can be many CSS & Script files and the head of your HTML can end up looking rather cumbersome. I built a little script that will load all of your files by passing them to the method as an Array. However, I have the loadCSS() in its own script file and I just invoke and pass in the Array in via a script tag in the HTML. Code is in monolithic format to make it easier to view.
在构建我们团队开发的应用程序时,可能会有许多CSS和脚本文件,并且HTML的头部最终看起来相当麻烦。我构建了一个小脚本,通过将它们作为数组传递给方法来加载所有文件。但是,我在自己的脚本文件中有loadCSS(),我只是通过HTML中的脚本标记调用并传入Array。代码采用单片格式,以便于查看。
window.onload = function() {//Use $(document).ready() if using jQuery
var cssArray = ["Style01.css", "Style02.css", "Style03.css"];
loadCSS(cssArray, function () {
alert("Style sheets have been loaded.");
});
//Note: You can do a similar process for the JS files.
//Load HTML when CSS is finished - Shown below
loadHTML();
}
function loadCSS(array, callback) {
var cssArray = array;
for (var i = 0; i < cssArray.length; i++)
{
document.write("<link rel='stylesheet' type='text/css' href='styles/" + cssArray[i] + "' />");
//console.log(cssArray[i] + " style sheet has been loaded.");
//Detects when for loop is finished evaluating the Array
if (i == cssArray.length - 1) {
return callback();
}
}
//loadHTML() can also be invoked here to ensure CSS files have been loaded.
}
If you are attempting to build out some HTML dynamically then you could try something like this after the CSS files are loaded.
如果你试图动态构建一些HTML,那么你可以在加载CSS文件后尝试这样的东西。
function loadHTML() {
//Create Main Table
var mainTable = document.createElement("table");
mainTable.id = "mainTable";
mainTable.cellPadding = 0;
mainTable.cellSpacing = 0;
mainTable.border = 0;
//Create Body
var mainBody = document.createElement("tbody");
//Create Table Row
var mainTR = document.createElement("tr");
mainTR.style.height = "50px";
mainTR.className = ""; //Insert class from one of the style sheets
//Create Main Cell
var mainTD = document.createElement("td");
mainTD.id = "mainTD";
//mainTD.style.width = "";
mainTD.style.textAlign = "left";
mainTD.style.padding = "5px 10px 5px 10px";
mainTD.className = ""; //Insert class from one of the style sheets
mainTD.innerHTML = "Test Text";
mainTR.appendChild(mainTD);
mainBody.appendChild(mainTR);
mainTable.appendChild(mainBody);
document.body.appendChild(mainTable);
}
If you have any questions please feel free to ask. Although there are already some good examples posted, hopefully this can help.
如果您有任何疑问,请随时提出。虽然已经发布了一些很好的例子,但希望这可以提供帮助。
#9
0
what about :
关于什么 :
$(document).ready(function() {
$("body").hide();
});
then, in the downloaded css files :
然后,在下载的css文件中:
body { diaplay:block; }
#10
0
Use loadCSS
to load your CSS
. and inside onload
method put your code you want to execute after all css load.
使用loadCSS加载CSS。并且内部的onload方法将你想要执行的代码放在所有css加载之后。
var counter = 0;
function onload(){
counter--;
setTimeout(function(){ // insuring if loaded immediately
if(counter == 0){
// your code here //******** CODEREPLACE ************/
alert('all css files loaded!');
}
});
}
function loadCSS(href){
counter++;
l = document.createElement('link');
l.href = href;
l.onreadystatechange = function () { // For IE
if (this.readyState == 'loaded'){
onload.call( this );
}
};
l.rel = 'stylesheet';
l.type='text/css';
l.onload = onload;
document.getElementsByTagName('head')[0].appendChild(l);
}
loadCSS('http://www.google.co.in/search?q=load+css+files+dynamically&aq=f&oq=load+css+files+dynamically&sugexp=chrome,mod=1&sourceid=chrome&ie=UTF-8');
#1
3
You could use YepNope.js, YepNope allows you to build asynchronous conditional tests to see whether resources have loaded. Once your tests have passed you can tell it to inject new CSS or JS files.
您可以使用YepNope.js,YepNope允许您构建异步条件测试以查看资源是否已加载。一旦你的测试通过,你可以告诉它注入新的CSS或JS文件。
Example below has been taken from the YepNope.js site.
以下示例取自YepNope.js站点。
yepnope.injectCss( stylesheetSource [, callback ] [, elemAttributes ] [, timeout ]);
// Example
yepnope.injectCss("print.css", function () {
console.log("css injected!");
}, {
media: "print"
}, 5000);
You can even make YepNope load the initial CSS files first and then once they have completed loading YepNope can trigger a callback to do additional tasks, such as loading more JS or CSS files.
您甚至可以让YepNope首先加载初始CSS文件,然后一旦完成加载,YepNope就可以触发回调来执行其他任务,例如加载更多JS或CSS文件。
#2
3
Source: https://*.com/a/3794242/1292652
Retreiving CSS text using AJAX
Instead of using messy workarounds to determine of the CSS has loaded, you can use AJAX function to create a dynamic CSS URL and fetch the it as plain text.
您可以使用AJAX函数创建动态CSS URL并将其作为纯文本格式获取,而不是使用凌乱的变通方法来确定已加载的CSS。
Inserting the CSS
After fetching the raw text, you can use this function to insert the CSS into a style
tag and add a callback:
获取原始文本后,您可以使用此函数将CSS插入样式标记并添加回调:
function loadCss(cssText, callback) {
var style = document.createElement('style');
style.type='text/css';
if(callBack != undefined){
style.onload = function() {
callback();
};
}
style.innerHTML = cssText;
head.appendChild(style);
}
Using it
And now you can use this as:
现在你可以用它作为:
loadCss(ajaxResponseText, function(){
console.log("CSS loaded, you can show the dialog now :)");
})
Allowing cross-domain AJAX
In your comment, you mentioned you had to load jQuery
and jQueryUI
which I'm guessing wil de on a different domain.
在你的评论中,你提到你必须加载jQuery和jQueryUI,我猜他们会在不同的域上。
To get around the AJAX cross-domain restriction, check out this link or this one or this library
要解决AJAX跨域限制,请查看此链接或此库或此库
#3
1
<html>
<head>
<!--
Put your styles here. Make sure the *last* CSS file has the following:
body { display: block !important }
This will allow the stylesheets to load while the body is hidden.
When the last stylesheet is loaded, the body will be visible.
-->
</head>
<body style="display: none">
<!-- Lots of HTML here -->
<!--
Put your script tags here.
In the first script, I recommend binding to the window.load event...
which will be fired once all your scripts are done loading.
-->
</body>
</html>
#4
0
I think this is somewhat along the lines of what you wanted:
我认为这有点像你想要的:
<html>
<head>
<!-- CSS Stuff goes here -->
<!-- JS Stuff come right after -->
</head>
<body>
<!-- HTML Stuff comes withing Body -->
</body>
</html>
This will cause:-
这将导致: -
- All the CSS files to download in parallel;
- Then the HTML stuff gets parsed and displayed;
- The browser gets all the JS;
- The JS is tun and it does whatever inserting it wants;
所有CSS文件并行下载;
然后解析并显示HTML内容;
浏览器获取所有JS;
JS是tun,它可以执行任何插入操作;
Your question is a bit confusing, can you clarify it? I didn't understand why you'd require to have such an order, can you give the big picture? JS is meant to be a fire-and-forget language, it will be awkard to see if everything's downloaded. Did this make sense to you and/or help you?
你的问题有点令人困惑,你能澄清一下吗?我不明白你为什么要这么订单,你能说出全局吗? JS本来就是一种昙花一现的语言,看看是否所有内容都下载都很麻烦。这对你有意义和/或帮助你吗?
#5
0
I know it is not a pretty solution, but you can fetch the CSS files using AJAX and add their content to a <style>
, instead of inserting a <link>
to the DOM. Using AJAX, you can know for sure when the CSS is completely downloaded and add the whole thing into the page under your terms.
我知道这不是一个漂亮的解决方案,但您可以使用AJAX获取CSS文件并将其内容添加到
#6
0
Source: https://*.com/a/8122005/1292652
I don't recommend this for the same reason why you shouldn't use a while
loop to implement sleep()
, but if you must, you can try it.
我不推荐这个,因为你不应该使用while循环来实现sleep(),但如果你必须,你可以试试。
In the linked answer, a reference style was added. For example: #ensure-cssload-8473649 { display: none }
. But since you're downloading files not in your control, you'll have to select a few styles from the sheet for detection.
在链接的答案中,添加了参考样式。例如:#ensure-cssload-8473649 {display:none}。但是,由于您下载的文件不在您的控件中,因此您必须从工作表中选择一些样式进行检测。
The cssLoad()
function is:
cssLoad()函数是:
var onCssLoad = function (options, callback) {
var body = $("body");
var div = document.createElement(constants.TAG_DIV);
for (var key in options) {
if (options.hasOwnProperty(key)) {
if (key.toLowerCase() === "css") {
continue;
}
div[key] = options[key];
}
}
var css = options.css;
if (css) {
body.appendChild(div);
var handle = -1;
handle = window.setInterval(function () {
var match = true;
for (var key in css) {
if (css.hasOwnProperty(key)) {
match = match && utils.getStyle(div, key) === css[key];
}
}
if (match === true) {
window.clearTimeout(handle);
body.removeChild(div);
callback();
}
}, 100);
}
}
You can use it as:
您可以将其用作:
onCssLoad({
"id": <insert element CSS applies to>,
css: <insert sample CSS styles>
}, function () {
console.log("CSS loaded, you can show the dialog now :)");
});
#7
0
Why don't you add an element on page and check some style that it should have with some js. If it has that style then that stylesheet is probably load.
为什么不在页面上添加元素并检查一些js应该具有的样式。如果它具有该样式,则该样式表可能已加载。
Like this:
if (document.getElementById("csspage-3-box").style.color === "#somethingUnique") {
//it is loaded
}
You could append a few hidden divs with IDs unique to each style sheet. If they have any styles at all then you know that the sheet you want is loaded. This operation is cheap. It does add some non-semantic div elements though. That being said, I feel like everyone has at least one non-semantic element in their DOM.
您可以附加一些隐藏的div,其中每个样式表都有唯一的ID。如果他们有任何样式,那么你知道你想要的表被加载。这个操作很便宜。它确实添加了一些非语义div元素。话虽这么说,我觉得每个人的DOM中至少有一个非语义元素。
Just a suggestion, but 3 css files isn't that many. Other easy solutions include the following:
只是一个建议,但3 css文件并不是那么多。其他简单的解决方案包括:
A) You could just cat and minify them and deliver them all at once.
B) Throw them onto a CDN (like aws s3 + cloudfront), which is super cheap and they will get loaded in parallel.
C) Just load them in as normal. You could also put them on a sub domain.
A)您可以将它们缩小并缩小它们并立即将它们全部送出。 B)将它们扔到CDN(如aws s3 + cloudfront)上,这是非常便宜的,它们将并行加载。 C)正常加载它们。您也可以将它们放在子域上。
Now that aside if I were you I'd divide my CSS down into a bunch of files. 3 is too few files. I'd separate out grid and every element type. Then re-assemble them on a per page basis (or page group). This allows you to include each individual piece as you need.
现在除了我是你,我将我的CSS分成一堆文件。 3文件太少了。我将网格和每种元素类型分开。然后在每页(或页面组)的基础上重新组装它们。这允许您根据需要包含每个单独的部分。
After all that it is fairly easily to append a link tag (as long as you can easily get a path to it). I recommend using the link instead of the style tag because if you do go the CDN route or subdomain route you will have issues with cross-domain issues if trying to grab the content of the css file with some xhr.
毕竟,附加链接标记相当容易(只要您可以轻松获得它的路径)。我建议使用链接而不是样式标记,因为如果你去CDN路由或子域路由,如果尝试使用某些xhr获取css文件的内容,则会出现跨域问题。
#8
0
In building the apps that our team develops there can be many CSS & Script files and the head of your HTML can end up looking rather cumbersome. I built a little script that will load all of your files by passing them to the method as an Array. However, I have the loadCSS() in its own script file and I just invoke and pass in the Array in via a script tag in the HTML. Code is in monolithic format to make it easier to view.
在构建我们团队开发的应用程序时,可能会有许多CSS和脚本文件,并且HTML的头部最终看起来相当麻烦。我构建了一个小脚本,通过将它们作为数组传递给方法来加载所有文件。但是,我在自己的脚本文件中有loadCSS(),我只是通过HTML中的脚本标记调用并传入Array。代码采用单片格式,以便于查看。
window.onload = function() {//Use $(document).ready() if using jQuery
var cssArray = ["Style01.css", "Style02.css", "Style03.css"];
loadCSS(cssArray, function () {
alert("Style sheets have been loaded.");
});
//Note: You can do a similar process for the JS files.
//Load HTML when CSS is finished - Shown below
loadHTML();
}
function loadCSS(array, callback) {
var cssArray = array;
for (var i = 0; i < cssArray.length; i++)
{
document.write("<link rel='stylesheet' type='text/css' href='styles/" + cssArray[i] + "' />");
//console.log(cssArray[i] + " style sheet has been loaded.");
//Detects when for loop is finished evaluating the Array
if (i == cssArray.length - 1) {
return callback();
}
}
//loadHTML() can also be invoked here to ensure CSS files have been loaded.
}
If you are attempting to build out some HTML dynamically then you could try something like this after the CSS files are loaded.
如果你试图动态构建一些HTML,那么你可以在加载CSS文件后尝试这样的东西。
function loadHTML() {
//Create Main Table
var mainTable = document.createElement("table");
mainTable.id = "mainTable";
mainTable.cellPadding = 0;
mainTable.cellSpacing = 0;
mainTable.border = 0;
//Create Body
var mainBody = document.createElement("tbody");
//Create Table Row
var mainTR = document.createElement("tr");
mainTR.style.height = "50px";
mainTR.className = ""; //Insert class from one of the style sheets
//Create Main Cell
var mainTD = document.createElement("td");
mainTD.id = "mainTD";
//mainTD.style.width = "";
mainTD.style.textAlign = "left";
mainTD.style.padding = "5px 10px 5px 10px";
mainTD.className = ""; //Insert class from one of the style sheets
mainTD.innerHTML = "Test Text";
mainTR.appendChild(mainTD);
mainBody.appendChild(mainTR);
mainTable.appendChild(mainBody);
document.body.appendChild(mainTable);
}
If you have any questions please feel free to ask. Although there are already some good examples posted, hopefully this can help.
如果您有任何疑问,请随时提出。虽然已经发布了一些很好的例子,但希望这可以提供帮助。
#9
0
what about :
关于什么 :
$(document).ready(function() {
$("body").hide();
});
then, in the downloaded css files :
然后,在下载的css文件中:
body { diaplay:block; }
#10
0
Use loadCSS
to load your CSS
. and inside onload
method put your code you want to execute after all css load.
使用loadCSS加载CSS。并且内部的onload方法将你想要执行的代码放在所有css加载之后。
var counter = 0;
function onload(){
counter--;
setTimeout(function(){ // insuring if loaded immediately
if(counter == 0){
// your code here //******** CODEREPLACE ************/
alert('all css files loaded!');
}
});
}
function loadCSS(href){
counter++;
l = document.createElement('link');
l.href = href;
l.onreadystatechange = function () { // For IE
if (this.readyState == 'loaded'){
onload.call( this );
}
};
l.rel = 'stylesheet';
l.type='text/css';
l.onload = onload;
document.getElementsByTagName('head')[0].appendChild(l);
}
loadCSS('http://www.google.co.in/search?q=load+css+files+dynamically&aq=f&oq=load+css+files+dynamically&sugexp=chrome,mod=1&sourceid=chrome&ie=UTF-8');