【问题标题】:Script is loaded before the jquery脚本在 jquery 之前加载
【发布时间】:2023-04-04 17:13:01
【问题描述】:

我正在尝试在我的应用程序中使用grapesjs。因此,我在 html 页面的头部添加了 jquery,在正文中添加了脚本。我的 jquery 已加载到该页面中,但在加载 jquery 之前,正文中的脚本已执行。使脚本不工作

JavaScript - How do I make sure a jQuery is loaded? 使用上面的链接,我尝试在标题标签中给出查询,在正文中给出脚本,但它不起作用。

<meta charset="utf-8">
<title>GrapesJS</title>
  <link rel="stylesheet" href="https://unpkg.com/grapesjs/dist/css/grapes.min.css">
  <script src="https://unpkg.com/grapesjs"></script>
  <style>
    body,
    html {
      height: 100%;
      margin: 0;
   }
  </style>
  <div id="gjs" style="height:0px; overflow:hidden;">
    <div class="panel">
      <h1 class="welcome">Welcome to</h1>
        <div class="big-title">
          <svg class="logo" viewBox="0 0 100 100">
            <path d="M40 5l-12.9 7.4 -12.9 7.4c-1.4 0.8-2.7 2.3-3.7 3.9 -0.9 1.6-1.5 3.5-1.5 5.1v14.9 14.9c0 1.7 0.6 3.5 1.5 5.1 0.9 1.6 2.2 3.1 3.7 3.9l12.9 7.4 12.9 7.4c1.4 0.8 3.3 1.2 5.2 1.2 1.9 0 3.8-0.4 5.2-1.2l12.9-7.4 12.9-7.4c1.4-0.8 2.7-2.2 3.7-3.9 0.9-1.6 1.5-3.5 1.5-5.1v-14.9 -12.7c0-4.6-3.8-6-6.8-4.2l-28 16.2"/>
         </svg>
         <span>GrapesJS</span>
       </div>
       <div class="description">
        This is a demo content from index.html. For the development, you shouldn't edit this file, instead you can
        copy and rename it to _index.html, on next server start the new file will be served, and it will be ignored by git.
    </div>
  </div>
 </div>

<script type="text/javascript">
  $(window).on('load', function(){
      var editor = grapesjs.init({
          showOffsets: 1,
          noticeOnUnload: 0,
          container: '#gjs',
          height: '100%',
          fromElement: true,
          storageManager: { autoload: 0 },
      });
  });

editor.BlockManager.add('testBlock', {
    label: 'Block',
    attributes: { class:'gjs-fonts gjs-f-b1' },
    content: `<div style="padding-top:50px; padding-bottom:50px; text-align:center">Test block</div>`
})

正文中的脚本必须在查询下载或解包后加载。

【问题讨论】:

  • 你的 jquery 包含脚本在哪里?
  • 你没有在任何地方包含或使用 jQuery
  • 这是完整的 HTML 文件吗?您似乎缺少&lt;head&gt;&lt;body&gt; 标签。您说您在 &lt;head&gt; 中包含 jQuery 脚本,但此处未显示。请包含完整文件,或澄清这是完整文件(在这种情况下,我们可以就必要的 HTML 元素、脚本和订单提供建议。

标签: javascript grapesjs


【解决方案1】:

您必须将脚本代码放在 document.ready 函数中,如下所示:

$(document).ready(function(){
  // your js code
});

或者像这样的window.load:

$(window).on('load', function(){
  // your js code
});

希望对你有帮助:)

【讨论】:

  • 这是错误的,因为页面上没有 jQuery,并且脚本无论如何都在文档的底部,因此无需等待加载或就绪事件
【解决方案2】:

把头部所有的js都取出来,加到body后面。 其次从html页面中取出所有脚本并创建一个新的js文件并在那里添加你的代码。

所以你的 html 文件看起来像这样

<body>
 //rest of html
<script src="pathToJquery"></script>
 <script src="https://unpkg.com/grapesjs"></script>
<script src="pathToCustomJS"></script>
</body>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多