javascript - 具有外部源和正文的脚本标签

标签 javascript html

我刚刚遇到 this sample code ,它有一个带有外部源和正文的脚本标签。我认为这是将一些信息传递给包含的脚本的聪明方法。 它是如何工作的?

<html>
  <head>
    <script src="http://unhosted.org/remoteStorage.js">{
      onChange: function(key, oldValue, newValue) {
        if(key=='text') {
          document.getElementById('textfield').value= newValue;
        }
      },
      category: 'documents'
    }</script>
  </head>

最佳答案

标签中包含的脚本在正常情况下不会被评估。我认为在您的示例中发生的事情是 remoteStorage.js 在评估内容时正在读取内容本身。像这样

//grab the last script tag in the DOM
//this will always be the one that is currently evaluating during load
var tags = document.getElementsByTagName('script');
var tag = tags[tags.length -1];
//force evaluation of the contents
eval( tag.innerHTML );

虽然这在标记中看起来很整洁,但我自己会使用单独的脚本标记并避免这种强制评估。

关于javascript - 具有外部源和正文的脚本标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8676093/

相关文章:

html - 如何使用 Bootstrap 4 制作 3x1 响应式页脚?

php - Jquery/PHP ajax 表单提交问题

javascript - AngularJS - 如何获取 ng-repeat 中每个项目的坐标?

javascript - Google map v3 - 土地类型

html - 匹配父类的XPath

html - 在内联 block 内垂直对齐 div

javascript - 如何使用 JavaScript 或 PHP 传回唯一 ID?

javascript - 使用 should.js 如何检查数组中是否不存在字符串?

jquery - django: Bootstrap 菜单不会在移动设备上折叠

html - Vimeo Embed : Custom Play Button working. 如何添加暂停按钮?