以编程方式编写CSS背景的最佳方法?

[英]Best way to programmatically CSS background?


I want to grab an image from my DB, and use that as the background. This is trivial, but is there a better/faster way than my current approach.

我想从我的数据库中获取图像,并将其用作背景。这是微不足道的,但是有一种比我目前的方法更好/更快的方式。

Currently, I use Javascript (in the <head>) to load my background image, since my CSS is linked and not internal:

目前,我使用Javascript(在中)加载我的背景图像,因为我的CSS是链接的而不是内部的:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type='text/javascript'>
    $(document).ready(function(){
        $('body').css('background', 'url(/_images/galleries/lg_<?php echo getBackgroundImage(); ?>) no-repeat top center white');
    });
</script>

Upon loading the page, it takes about a half second to load the background. I assume the delay can be attributed to loading the external JS, etc. Also, the above code is included as a component, such that I don't have to copy/paste that code in each page of the website. The <body> is not encompassed in this included component.

加载页面后,加载背景大约需要半秒钟。我假设延迟可以归因于加载外部JS等。此外,上面的代码作为组件包含在内,这样我就不必在网站的每个页面中复制/粘贴该代码。 不包含在此包含的组件中。

Is there a FASTER and preferable approach?

有更快更好的方法吗?

2 个解决方案

#1


6  

Since you're adding a script to the document you could probably just add a <style> block with the CSS you need.

由于您要在文档中添加脚本,因此您可以使用所需的CSS添加

#2


0  

I see this has been answered already however...

我看到已经回答了这个问题......

I assume the delay can be attributed to loading the external JS

我认为延迟可归因于加载外部JS

Yes. Javascript blocks by default. While there are ways around this, they depend on defering the loading of the javascript. And you're still having to wait for the javascript to load before it can load the graphic to put in the background. Using j08691's method avoids this issue, but if you want the script to go faster still then inline the image data within the CSS file (you could do it in the HTML, but then caching of the image is restricted by caching of the html - usually CSS files will be more cache-able). Of course if you want to support older browsers then you'll need a Varies: User-agent header and different code for non-compliant browsers.

是。默认情况下是Javascript块。虽然有办法解决这个问题,但它们依赖于推迟加载javascript。并且你仍然需要等待javascript加载才能加载图形以放入后台。使用j08691的方法避免了这个问题,但如果你想让脚本更快地运行,那么内联CSS文件中的图像数据(你可以在HTML中进行,但是然后通过缓存html来限制图像的缓存 - 通常CSS文件将更加缓存。当然,如果您想支持旧浏览器,那么您将需要Varies:User-agent标头和不兼容浏览器的不同代码。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.itdaan.com/blog/2012/05/30/6f859f382540a91f7a033d1fef4d9df0.html



 
© 2014-2019 ITdaan.com 粤ICP备14056181号