簡體   English   中英

如何在localStorage中存儲JavaScript或CSS文件

[英]How to store javascript or a css file in localStorage

如何以編程方式在瀏覽器的本地存儲中 存儲特定的JavaScript或CSS文件,如何在需要時將其檢索,如果當前會話到期,則將其從本地存儲中刪除。

讓我們通過這個例子(偽代碼)來理解:

var load_from_server = true;
if (detect local storage)  
{
  if (cache of css, js found)
  {
     load the css and js from local storage cache
     load_from_server = false;
  }
}
if (load_from_server)
{
   document.write('<script>...');
}

$( window ).unload(function() {
  clear local storage cache
});

我需要這樣的東西。 我提到了很多博客和QA的堆棧溢出問題,但是沒有得到,但沒有得到我真正想要的東西。 請建議我該怎么做

您不能將文件存儲在本地存儲中。 但是您可以使用html5清單來存儲html,css,js和圖像。

檢查其他線程以獲取更多詳細信息。

在本地存儲中存儲CSS和JS

簡而言之,是的,但我不建議您這樣做。 嘗試閱讀此內容,它與您的問題相同: https : //softwareengineering.stackexchange.com/questions/105524/is-it-realistic-to-make-use-of-html5-local-storage-to-store-css和JavaScript

好吧,這對我有用。 如果您還將最后更改日期的變量存儲在localstorage中,並將另一個變量傳遞給腳本,則無需在離開頁面時清除存儲。 您可以比較兩個日期,並僅在必要時從服務器加載較新的腳本。 如果用戶返回頁面,特別是在連接速度較慢時,它將提高性能。

從服務器加載腳本:

jQuery.loadScript(<your_script_url>);
jQuery.loadScript = function (url) {    
    jQuery.ajax({
        url: url,
        dataType: 'script',
        cache: false,   
        async: true,
        success: function(response){            
            save_script_in_local_storage(response);         
        }
    });
}

將其保存在本地存儲中:

function save_script_in_local_storage(script){
    try{
        if (typeof(Storage) !== "undefined" && typeof localStorage !== "undefined" && localStorage !== null && typeof localStorage.setItem === 'function') {
localStorage.setItem("my_script", JSON.stringify(script));
}
    }catch(e){
        console.log(e);
    }
}

從本地存儲加載腳本:

if (!load_from_server){
   try{
        if (typeof(Storage) !== "undefined" && typeof localStorage !== "undefined" && localStorage !== null && localStorage.getItem("my_script") !== null) {
           var my_script = JSON.parse(localStorage.getItem('my_script'));
           $('<script>')
                .attr('type', 'text/javascript')
                .attr('id', 'my_script')
                .text(my_script)
                .appendTo('head');
        }else{                  
           jQuery.loadScript(<your_script_url>);
        }
  }catch(e){
     jQuery.loadScript(<your_script_url>);
  }
}

暫無
暫無

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

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