Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
477 views
in Technique[技术] by (71.8m points)

html - What are the ways to load JavaScript or CSS without executing them?

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);

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)

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?

UPDATE:

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Just found out one more option to load script/css asynchronously (without conflicting to SOP) - is to use <object> tag:

<object data="http://podlipensky.com/examples/dynamicscript/hey.js" />

Found this approach here. So I'm just sharing with you my findings, hope it will be useful.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...