简体   繁体   English

如何在脚本标记中为src设置本地存储值

[英]How to set local storage value for src in script tag

I want to set local storage value in bellow script code. 我想在下面的脚本代码中设置本地存储值。

<html>
 <head>
    <script type="text/javascript" src="here I want to set file name"></script>
</head>
</html>

I want to set file path which is stored/saved in local storage . 我想设置在本地存储中存储/保存的文件路径。 I Want to do like this 我想这样

  <script type="text/javascript" src= localStorage.getItem('languageFilePath')>

the HTMl file is my index file of application HTMl文件是我的应用程序索引文件

You can use HTMLScriptElement API. 您可以使用HTMLScriptElement API。 Check the Dynamically importing scripts . 检查动态导入脚本 I used their code to show you how you can do the same. 我用他们的代码向您展示了如何做到这一点。

<html>
<head>
</head>
<body>
  <script type="text/javascript">
    function loadError (oError) {
      throw new URIError("The script " + oError.target.src + " is not accessible.");
    }

    function importScript (sSrc, fOnload) {
      var oScript = document.createElement("script");
      var oHead = document.head || document.getElementsByTagName("head")[0];

      oScript.type = "text\/javascript";
      oScript.onerror = loadError;
      if (fOnload) { oScript.onload = fOnload; }
      oHead.appendChild(oScript);
      oScript.src = sSrc;
      oScript.defer = true;
    }

    importScript(localStorage.getItem('languageFilePath'));
  </script>
</body>
</html>

A little background what defer attribute does.. 稍微了解一下defer属性的作用。

For classic scripts, if the async attribute is present, then the classic script will be fetched in parallel to parsing and evaluated as soon as it is available (potentially before parsing completes). 对于经典脚本,如果存在async属性,则将与解析并行获取经典脚本,并在可用时立即对其进行评估(可能在解析完成之前)。 If the async attribute is not present but the defer attribute is present, then the classic script will be fetched in parallel and evaluated when the page has finished parsing. 如果async属性不存在,而defer属性存在,则经典脚本将以并行方式获取并在页面完成解析后进行评估。 If neither attribute is present, then the script is fetched and evaluated immediately, blocking parsing until these are both complete. 如果两个属性都不存在,则立即获取脚本并对其进行评估,阻止解析,直到两个都完成为止。

You can do something as simple as this, using the DOMContentLoaded event. 您可以使用DOMContentLoaded事件来做到这一点。

As soon as the initial HTML document has been completely loaded and parsed, the event fire and your script will load. 初始HTML文档被完全加载和解析后,事件将触发并且您的脚本将被加载。

<head>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            var s = document.createElement('script');
            s.setAttribute('type', 'text/javascript');
            s.setAttribute('src', localStorage.getItem('languageFilePath'));
            document.getElementsByTagName('head')[0].appendChild(s);    
        })     
    </script>
</head>

Here is some more read on how to load script dynamically 这是有关如何动态加载脚本的更多信息


The above script fragment were taken/simplified from what I personally use for my web pages, to support older browsers as well. 上面的脚本片段是从我个人用于网页的内容中提取/简化的,以也支持较旧的浏览器。

var DomLoaded = {
    done: false, onload: [],
    loaded: function () {
        if (DomLoaded.done) return;
        DomLoaded.done = true;
        if (document.removeEventListener) { document.removeEventListener('DOMContentLoaded', DomLoaded.loaded, false); }
        for (i = 0; i < DomLoaded.onload.length; i++) DomLoaded.onload[i]();
    },
    load: function (fireThis) {
        this.onload.push(fireThis);
        if (document.addEventListener) {
            document.addEventListener('DOMContentLoaded', DomLoaded.loaded, false);
        } else {
            /*IE<=8*/
            if (/MSIE/i.test(navigator.userAgent) && !window.opera) {
                (function () {
                    try { document.body.doScroll('up'); return DomLoaded.loaded(); } catch (e) { }
                    if (/loaded|complete/.test(document.readyState)) return DomLoaded.loaded();
                    if (!DomLoaded.done) setTimeout(arguments.callee, 10);
                })();
            }
        }
        /* fallback */
        window.onload = DomLoaded.loaded;
    }
};

DomLoaded.load(function () {
    var s = document.createElement('script');
    s.setAttribute('type', 'text/javascript');
    s.setAttribute('async', true);
    s.setAttribute('defer', true);
    s.setAttribute('src', '/demo_files/script.js');
    document.getElementsByTagName('head')[0].appendChild(s);
});

you can do simply by assigning id to script tag 您只需将id分配给脚本标签即可

<script type="text/javascript" id="script_tag">

and then set attribute of src in onload method of body, like below code. 然后在body的onload方法中设置src的属性,如下面的代码所示。

<html>
  <head>
   <script type="text/javascript" id="script_tag"></script>
  </head> 

<body onload="assignData()">
 <script>
    function assignData() {
      document.getElementById('script_tag').setAttribute('src', 
        window.localStorage.getItem('languageFilePath'));
    }
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM