我可以根据要求加载外部样式表吗? [英] Can I load external stylesheets on request?

查看:80
本文介绍了我可以根据要求加载外部样式表吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$.getScript('ajax/test.js', function() {
  alert('Load was performed.');
});

..就像上面的代码可应要求加载外部JS一样,是否有类似的功能可用于在需要时加载外部CSS样式表?

例如,当我在网站上使用灯箱(嵌入式弹出窗口)时,除非用户要求,否则我希望避免在加载时加载灯箱JS和CSS文件.

谢谢

解决方案

是的:如果您创建链接到样式表的<link>标签并将其添加到<head>标签,浏览器将加载该样式表.

例如

$('head').append('<link rel="stylesheet" type="text/css" href="lightbox_stylesheet.css">');

但是根据@peteorpeter的评论,这在IE 8或更低版本中不起作用-在那儿,您需要执行以下操作之一:

  1. 在设置href之前在<link> 之前附加;或
  2. 使用IE的document.createStyleSheet()方法

此外,检查是否已添加链接不能在所有浏览器中可靠地工作.

我还会质疑您的前提的一部分:

除非用户要求,否则我想避免加载灯箱JS和CSS文件.

为什么?减轻页面重量?我可以理解这种需求,但是您应该使用其中的灯箱代码来衡量CSS和JS文件的大小(在缩小和gzip后),如果没有,请查看减少大小是否值得:

  1. 按需加载增加了复杂性;和
  2. 灯箱的响应性略有降低(因为按需加载时,灯箱必须先等待自己的CSS和JS加载,然后才能完成工作)

经过压缩和压缩后,差异可能不会太大.

请记住,您可以指示浏览器长时间缓存CSS和JS,这意味着只有当用户访问您的网站且缓存为空时,它才会被下载.

$.getScript('ajax/test.js', function() {
  alert('Load was performed.');
});

.. like the above code which loads an external JS on request, is there something similar available to load an external CSS stylesheet when required?

Like for example when I use lightboxes (inline popups) on my site, I want to avoid loading lightbox JS and CSS files onload, unless requested by the user.

Thanks

解决方案

Yup: if you create a <link> tag linking to a stylesheet and add it to the <head> tag, the browser will load that stylesheet.

E.g.

$('head').append('<link rel="stylesheet" type="text/css" href="lightbox_stylesheet.css">');

However, as per @peteorpeter’s comments, this doesn’t work in IE 8 or under — there, you need to either:

  1. append the <link> before setting its href; or
  2. use IE’s document.createStyleSheet() method

Also, checking whether a link has already been added doesn’t work reliably across all browsers.

I would also question part of your premise:

I want to avoid loading lightbox JS and CSS files onload, unless requested by the user.

Why? To reduce page weight? I can understand the desire, but you should measure the size of your CSS and JS files (after minification and gzipping) with the lightbox code in there, and without, to see whether the reduction is worth:

  1. the added complexity of loading on-demand; and
  2. the slightly reduced responsiveness of the lightbox (because when loading on-demand, the lightbox will have to wait for its own CSS and JS to load before it can do its thing)

After minification and gzipping, there may well not be that much difference.

And bear in mind that you can instruct the browser to cache your CSS and JS for a long time, meaning it only gets downloaded when a user visits your site with an empty cache.

这篇关于我可以根据要求加载外部样式表吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆