2

css ファイルまたは javascript ファイルを HTML ドキュメントの head タグに動的に挿入する方法はありますか。

シナリオは次のとおりです。

ajax 呼び出しを行うと、基本的に HTML が返され、css とイベントが別のファイルに保存されます。

私が必要としているのは、リンクとスクリプトを head タグに入れることです。

4

2 に答える 2

1

外部JavaScriptの読み込みはjQueryに組み込まれていますが、CSS要素を作成する必要があります。

$(document).ready( function(){

    $("head").append("<link>");
    css = $("head").children(":last");
    css.attr({
      rel:  "stylesheet",
      type: "text/css",
      href: "/link/to/your.css"
    });
    $.getScript("/path/to/your.js", function(){
         // fires after JS is loaded
    });

});

外部ファイルを取得するには、jQueryを読み込んで、このJavaScriptをページで実行できる必要があります。

私はGoogleを使用して検索しました:http://topsecretproject.finitestatemachine.com/2009/09/how-to-load-javascript-and-css-dynamically-with-jquery/

于 2012-05-09T14:50:15.053 に答える
1

jQuery メソッドは IE では機能しませんが、独自の特別なcreatStyleSheet関数で処理できます。

var url = '/b/css/datepicker.jquery-ui.css';

if (document.createStyleSheet){
  document.createStyleSheet(url);
 } else {
   $('head').append('<link rel="stylesheet" type="text/css" href="' + url + '"/>');
 }
于 2012-05-09T14:51:22.753 に答える