有没有办法从字符串中加载 css 和 javascript? [英] Is there any way to load css and javascript from a string?

查看:33
本文介绍了有没有办法从字符串中加载 css 和 javascript?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我见过很多从文件中动态加载 CSS 和 javascript 的例子.这是一个很好的例子.但是有没有办法将 CSS 或 javascript 作为字符串加载?例如,类似于:

I've seen many examples of loading CSS and javascript dynamically from a file. Here's a good example. But is there a way to load CSS or javascript as a string? For example, something like:

var style = ".class { width:100% }"
document.loadStyle(style);

或者类似的东西.

推荐答案

var javascript = "alert('hello');";
eval(javascript);

这将从字符串加载 JavaScript,但请注意,这是非常不安全的,不推荐使用.如果恶意进程干扰了您的 JavaScript 字符串,则可能会导致安全问题.

This will load the JavaScript from a string, but be warned that this is highly insecure and not recommended. If a malicious process ever interfered with your string of JavaScript, it could result in security issues.

就 CSS 而言,您可以使用 jQuery 将样式标记附加到页面,如下所示:

As far as CSS goes, you can append a style tag to the page using jQuery, like so:

$('head').append("<style>body { background-color: grey; }</style>");

或者,对于 JavaScript 纯粹主义者:

Or, for the JavaScript purists:

var s = document.createElement("style");
s.innerHTML = "body { background-color:white !important; }";
document.getElementsByTagName("head")[0].appendChild(s);

这篇关于有没有办法从字符串中加载 css 和 javascript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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