开发者

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜