簡體   English   中英

使用外部JavaScript庫的動態html鏈接標記

[英]Dynamic html link tag using external javascript library

這個問題與先前的帖子有關: 檢查用戶是否正在使用位於中國的瀏覽器

我正在加載一個外部js庫,以評估要在標頭中加載的CSS。 按照上面提到的帖子的可接受答案,我將userinfo.io API加載到HTML頭中,然后對接收到的數據進行評估。 這是我所做的:

<head>

...

<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/userinfo/1.0.0/userinfo.min.js"></script>

<script type="text/javascript">
    UserInfo.getInfo(function(data) {
       // the "data" object contains the info
       if (data.country.code == 'CN') {
          // Load fallback fonts
          document.write('<link href="http://fonts.useso.com/css?family=Source+Sans+Pro:200,400,700|Dancing+Script:400,700|PT+Serif|Open+Sans:400,300,700" rel="stylesheet" type="text/css">');
       } else {
          // Load google fonts
          document.write('<link href="http://fonts.googleapis.com/css?family=Source+Sans+Pro:200,400,700|Dancing+Script:400,700|PT+Serif|Open+Sans:400,300,700" rel="stylesheet" type="text/css">');
       }
    }, function(err) {
       // the "err" object contains useful information in case of an error
    });
</script>

</head>

在Firefox中調試js,我可以看到該庫已成功加載。 第一次發生的是,我收到一條錯誤消息“參考錯誤:未定義UserInfo”。 我在html頭中按行的順序播放了一些(還有更多的CSS包括,一些元標記和標題)。 放完后

<head>

<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/userinfo/1.0.0/userinfo.min.js"></script>

...

<script type="text/javascript">
    UserInfo.getInfo(function(data) {
       // the "data" object contains the info
       if (data.country.code == 'CN') {
          // Load fallback fonts
          document.write('<link href="http://fonts.useso.com/css?family=Source+Sans+Pro:200,400,700|Dancing+Script:400,700|PT+Serif|Open+Sans:400,300,700" rel="stylesheet" type="text/css">');
       } else {
          // Load google fonts
          document.write('<link href="http://fonts.googleapis.com/css?family=Source+Sans+Pro:200,400,700|Dancing+Script:400,700|PT+Serif|Open+Sans:400,300,700" rel="stylesheet" type="text/css">');
       }
    }, function(err) {
       // the "err" object contains useful information in case of an error
    });
</script>

</head>

作為head標簽的第一行,它開始實際識別對象UserInfo及其方法getInfo() 同時,當我將行放回原始位置時(例如在第一個代碼段中),它還會識別該功能。 這種行為使我不知道在加載html頁面時如何在head標簽中執行javascript。 是否有可能在加載庫之前偶爾調用該方法?

無論如何,現在成功導入userinfo.io庫后,該站點將無法正確加載。 看一下瀏覽器控制台,我看到:

Broser控制台輸出

看一下我頁面的源代碼,我只看到正確加載的鏈接標記,但是頁面的其余部分丟失了。

在此處輸入圖片說明

所以這是我的假設:

我不能以某種方式在head標記中使用document.write() ,因為它會干擾頁面加載。 頁面成功加載后,我更有可能應該通過getElementById()訪問和修改鏈接標記。 因此,實際上我將使用jQuery的ready()函數來觸發此操作,以確保該庫已成功加載? 對於這些想法,我將不勝感激。

document.write()是一個非常危險的函數(對於網頁)。 您應該更具體地說明要在哪里寫東西(而不是整個文檔!)。 因此,您可以在HTML中指定一個空的div塊,並為其分配一個ID:

<div id="writehere"></div>

然后,在您的JavaScript中,您將執行以下操作:

var place;  //global variable

並在某些頁面初始化函數中執行此操作:

place=document.getElementById("writehere");

之后,您可以在任何地方進行所需的所有寫作,例如:

place.innerHTML += "Special output text<br />";

您甚至可以重寫它(修改innerHTML時使用“ =”而不是“ + =”)。

我承認,我可能錯過了您在“問題”中提出的要點之一。 我現在得到的印象是,您想為頁面指定額外的內容以便在加載過程中加載,而不一定總是相同的額外內容。 我不確定head部分是否是嘗試這樣做的正確位置,因為我不知道強制瀏覽器注意head部分中新添加的link項。 我確實知道它可以注意某些事情,例如在本示例中(當代碼由與body標簽相關聯的onload事件onload ,會將圖標放入瀏覽器標簽或瀏覽器窗口的左上角) ):

var hd, itm;

hd = document.getElementById('ID_of_Head');
itm = document.createElement('link');
itm.id = 'whatever';
itm.rel = 'shortcut icon';
itm.type = 'image/png';
itm.href = 'desired URL'; //OOPS; my comment below wrongly says 'src' property
hd.appendChild(itm);
//you can now re-use the 'itm' variable to specify another link, if you wish

appendChild()函數可能足以觸發瀏覽器注意新添加的鏈接,在這種情況下,這可能是通用的,而不僅限於此特定示例。 另一方面,我沒有嘗試添加多個link 一次可能只有其中一個可以被“關注”。 不過,在那種情況下,仍然存在一種方法,涉及一系列功能,每個功能都指定僅向head添加一個link 在每個函數的最后,您將執行以下操作:

setTimeout('nextlinkfunc();', 200);  //give each function a different name!

當前link功能結束時,它將設置計時器,並使瀏覽器有機會注意剛剛添加的link 200毫秒(1/5秒)后,計時器觸發指定的下一個功能-您將在其中指定向head添加另一個link 該函數的最后一件事是第三個函數的另一個setTimeOut() ,具有自己的唯一名稱。...對此的變體可能是更復雜的單個函數,其中使用一個參數來指定要進行哪個“調用”函數的名稱(當然,對函數的第一次調用必須指定參數值1 ):

//Note need to declare the global 'hd' and 'itm' variables,
// and set the 'hd' variable, before calling this function the first time
function nextlinkfunc(p)
{ itm = document.createElement('link');
  //more stuff as previously presented
  switch(p++)
  { case 1: //Note each 'case' block could have extra 'conditional' code
      itm.href = "URL_of_1st_link";
      break;
    case 2: //Conditional code can encompass many different combinations of URLs
      itm.href = "URL_of_2nd_link";
      break;
    //etc
  }
  hd.appendChild(itm);
  if(p<max_number_of_links_you_want_to_add)
    setTimeout('nextlinkfunc('p');', 200);
}

好吧,這很好! 謝謝。

<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/userinfo/1.0.0/userinfo.min.js"></script>

<script type="text/javascript">
  UserInfo.getInfo(function(data) {

    var elHead, elLink;

    elLink = document.createElement('link');
    elLink.rel = 'stylesheet';
    elLink.type = 'text/css';

    if (data.country.code == 'CN') {
      elLink.href = 'http://fonts.useso.com/css?family=Source+Sans+Pro:200,400,700|Dancing+Script:400,700|PT+Serif|Open+Sans:400,300,700';
    }else{
      elLink.href = 'http://fonts.google.com/css?family=Source+Sans+Pro:200,400,700|Dancing+Script:400,700|PT+Serif|Open+Sans:400,300,700';
    }

    elHead = document.getElementsByTagName("head")[0];

    elHead.appendChild(elLink);

  }, function(err) {

  });
</script>

...

<body onload="UserInfo.getInfo();">

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM