jq的getScript函數不支持chaset?override掉!

其實我歷來不用jq或者其餘框架的,這兩天偶然在一個小項目裏面發現jq的一個小bug:getScript函數沒有透傳charset信息,若是試圖在頁面上加載一個跨編碼的腳本的時候會致使編碼錯誤。寫了一個補丁函數覆蓋掉原來的:

$.getScript= function(url, callback , charset){
    $.ajax({
        url: url,
        dataType: "script",
        success:callback,
        scriptCharset:charset
    })
}    

這幾年代碼寫得不多,輕噴。這裏是 demo代碼 ,同時也到jq的github上提交了 一個issue

<! DOCTYPE html >
< HTML >
< HEAD >
< meta  charset ="utf-8"   />
< script  src ="http://cdn.jsdelivr.net/jquery/1.11.1/jquery.js" ></ script >

< SCRIPT  LANGUAGE ="JavaScript" >
<!--
function  log(s){
    $(
" body " )[ 0 ].innerHTML += " <p> " + s.replace( / \n / g, " <br> " ).replace( / \t / g, " &nbsp&nbsp&nbsp&nbsp " ) + " </p> " ;
}
function  testBIG5(result){
    log(
" BIG5 decode  " + (result ? " correctly " : " <font color=red>incorrectly</font> " ))
}
function  testGB(result){
    log(
" gb2312 decode  " + (result ? " correctly " : " <font color=red>incorrectly</font> " ))
}
function  testUTF8(result){
    log(
" utf-8 decode  " + (result ? " correctly " : " <font color=red>incorrectly</font> " ));
}
function  testJP(result){
    log(
" iso-2022-jp decode  " + (result ? " correctly " : " <font color=red>incorrectly</font> " ));
}
function  testKR(result){
    log(
" euc-kr decode  " + (result ? " correctly " : " <font color=red>incorrectly</font> " ));
}
$(document).ready(
function (){

    $.when(
        log(
" <i>old version of getScript:</i> " ),
        log($.getScript.toString()),
        $.getScript(
" http://stonelf.sinaapp.com/testGB.js " ),
        $.getScript(
" http://stonelf.sinaapp.com/testUTF8.js " ),
        $.getScript(
" http://stonelf.sinaapp.com/testBIG5.js " ),
        $.getScript(
" http://stonelf.sinaapp.com/testJP.js " ),
        $.getScript(
" http://stonelf.sinaapp.com/testKR.js " )
    ).then(
function (){

        $.getScript
= function (url, callback , charset){
            $.ajax({
                url: url,
                dataType: 
" script " ,
                success:callback,
                scriptCharset:charset
            })
        }    

        log(
" <hr><i>new versioni of getScript:</i> " );
        log($.getScript.toString()),
        $.getScript(
" http://stonelf.sinaapp.com/testGB.js " ,undefined, " gb2312 " );
        $.getScript(
" http://stonelf.sinaapp.com/testUTF8.js " ,undefined, " utf-8 " );
        $.getScript(
" http://stonelf.sinaapp.com/testBIG5.js " ,undefined, " big5 " );
        $.getScript(
" http://stonelf.sinaapp.com/testJP.js " ,undefined, " iso-2022-jp " );
        $.getScript(
" http://stonelf.sinaapp.com/testKR.js " ,undefined, " euc-kr " );

    })
})
// -->
</ SCRIPT >
</ HEAD >
< BODY >
</ BODY >
</ HTML >
相關文章
相關標籤/搜索