简体   繁体   中英

Using javascript to replace a stylesheet href before it is downloaded from server

Is it possible to block the downloading of external scripts/stylesheets with a bit of javascript? For example, putting a tiny block of javascript at the very top of <head> to do some operation on all <script> and <link> tags in the document, perhaps changing relative paths to absolute paths, before their original relative-path'd sources are downloaded from the server?

I am not looking for alternatives such as server-side processing or manually altering the <script> and <link> tags. I am interested in a proof-of-concept for the scenario where i have no control over the final document or it's generation except for inserting a single script tag.

No, you cannot.

The problem is in the head of the document the script will not have access to the nodes that are not yet loaded, so it cannot modify any script tags that will be coming up.

Also, the browser loads JavaScript as soon as it gets to the script tag and halt parsing the html until the script tag completes.

That means, there is no way of doing it with JavaScript.

May be something about this:?

$(function(){
    $("link").each(function(){
        $(this).attr('href','NEW_URL.css');
    });   
});

This will change the href attributes of all elements, but I can't assure that it will change the styles, because this script will be executed when DOM is ready.

PS It's not pure javascript - it's jQuery (sorry, if you needed pure javascript)

PPS - I've just tried this - CSS is applied. It doesn't mean that you can block downloading the css files, that are written in tag. They are downloaded, but when DOM is ready (document is loaded) - styles are changed. It's pretty fast - you wan't be able to see old styles =)

Well CSS works rather interesting, in the sense of how dynamic it is. That being said, you can use javascript to update the URL of the css after it downloaded and it's effects will be nullified when the link changes (99% sure).

If the above fails, CSS is again amazing, meaning you can insert a new link node, to a new CSS that basically overwrites any and all previous css styles to that of your own choosing.

What are you trying to achieve?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM