在不执行JavaScript或CSS的情况下加载JavaScript或CSS有哪些方法? [英] What are the ways to load JavaScript or CSS without executing them?

查看:126
本文介绍了在不执行JavaScript或CSS的情况下加载JavaScript或CSS有哪些方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过添加< style> < link> ,我知道动态脚本/ css加载标记到页面的主体或主体,但是一旦下载它将由浏览器执行。我正在考虑其他下载方式但不执行javascript / css代码。首先我想到的是XMLHttpRequest:

I'm aware of dynamic script/css loading by adding <style> or <link> tags to head or body of the page, but then it will be executed by browser once downloaded. I was thinking about other ways to download but do not execute javascript/css code. First what comes in my mind was XMLHttpRequest:

//simple execution received script
var executeScript = function(code){
    eval(code);
};
//create XMLHttpRequest in cross-browser manner
var xhr = createXMLHTTPObject();
//check whether file is loaded
var checkStatus = function(){
    if(xhr.readyState  == 4){
        if(xhr.status >= 200 && xhr.status < 300 || xhr == 304){
            executeScript(xhr.responseText);   
        }
        else {//error
        }
    }
};
//do request
xhr.open('get','http://podlipensky.com/examples/dynamicscript/hey.js', true);
xhr.onreadystatechange = checkStatus;
xhr.send(null);

但是在这种情况下,由于同源策略,我们受到来自同一域的脚本的限制(虽然我们可以尝试使用 CORS

But in this case we're limited with scripts from the same domain because of the Same Origin Policy (although we can try workaround it with CORS)

我想到的另一种方法是动态添加 iframe 到页面然后将脚本标记添加到 iframe ,因此脚本将在下载后执行,但它会发生在另一个页面的上下文中 - iframe

Another approach, I was thinking about is to add dynamically iframe to the page and then add script tag to the iframe, so the script will be executed once it downloaded, but it happens in context of another page - iframe.

还有其他方法可以下载而不执行脚本吗?

Are there any other ways to download and not execute the script?

更新:

下载有用的原因之一,但不执行javascript / css是预先加载第三方库,但仅在需要时使用它们。

One of the reasons why it would be useful to download, but not execute javascript/css is to pre-load third-party libraries, but use them only on demand.

推荐答案

你可以还可以使用 iframe 并使用script / css URL作为框架的 src (因此它根本不被评估/应用),尽管在这种情况下你想要确保JavaScript / CSS与Content-Type text / plain 一起提供,以避免在< 字符等情况下发生不幸事件。虽然你应该在这个方法上遇到SOP问题,但是在一个不错的浏览器上,如果 iframe src 来自另一个来源。

You can also use an iframe and use the script/css URL as the src of the frame (so it isn't evaluated/applied at all), although you'd want to be sure in that case that the JavaScript/CSS was delivered with Content-Type text/plain to avoid unfortunate things happening with < characters and such. Although you should run into SOP issues with this approach as well, on a decent browser, if the iframe src is from a different origin.

除此之外,我认为你在很大程度上已经列出了你所列出的选项。

Other than that, I think you largely have it covered with the options you list.

这篇关于在不执行JavaScript或CSS的情况下加载JavaScript或CSS有哪些方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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