简体   繁体   中英

Inject HTML and CSS using jquery but have the CSS in a separate file?

I'm building something that is going to inject HTML into a users website via Jquery hosted on my server (their just going to include my script like they do other Javascript already).

So I have my HTML injecting; how can I not write inline style CSS with the injected HTML?

The only idea I have is to query my server for this external javascript file at the beginning of my Jquery. I'm not sure how to make both the CSS and Jquery available to the user's browser though.

Any thoughts? I'm doing something like the below, FYI.

$(document).ready(function() {
$('body').find(":last").after("
<div class='spacer'></div><div id='nav_menu_wrapper'><div class='nav_menu'>");
});

You can use jQuery to inject a <link> tag with the href pointing to wherever you serve the script:

$('head').append(
    $('<link/>', {href: '//path.to/your/stylesheet.css', rel: 'stylesheet'})
);

You can append a CSS on head .

$("<link />").attr({ "href": "link",
    "rel": "stylesheet",
    "type": "text/css" })
    .appendTo("head");

Or make a request and create a style tag.

$.get("/static/default.css", function(d)
{
    $("<style />").html(d).appendTo("head");
})

As for appending html you can make a $.get and append or use an iframe .

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