Loading JS/JQuery in Extend > Widgets
-
We didn't have any issues loading js/jquery in version 2, however when we use the same scripts in version 3, the scripts get loaded only when we navigate to another page.
So on initial page load (index page/category list), we get ReferenceError: $ is not defined error in browser console. Once we navigate to another page, say topic lists, the js gets loaded.
How do we ensure that our js (in widgets) loads on page load? We already have $(document).ready function on our scripts. Thanks!
-
@Teemberland I had a similar issue, and needed to use the below as a workaround - you'll obviously need to modify it, but I think you'll get the idea
<head> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.0/jquery.min.js" integrity="sha512-3gJwYpMe3QewGELv8k/BX9vcqhryRdzRMxVfq6ngyWXwo03GFEzjsUm8Q7RZcHPHksttq7/GFoxjCVUjkjvPdw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> </head> <script src="/assets/js/cbg.js"></script> <div id="cbg" class="cbgresult"></div> <div class="generate"> <button id="reloadme" class="btn btn-primary">Generate Another</button> </div> <script> $(function() { // after page load $('.cbgresult').fadeOut(0, function() { $("#cbg").show(); $(this).html(phrase()); }); }); $(document).ready(function(){ $("#cbg").show(); $('#reloadme').click(function(){ $("#cbg").html(phrase()); }); }); </script>
-
@phenomlab ohhh very interesting! Thank you, I'll go ahead and try this now.
-
@Teemberland you can probably test quickly by adding the below at the top of the widget code
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.0/jquery.min.js" integrity="sha512-3gJwYpMe3QewGELv8k/BX9vcqhryRdzRMxVfq6ngyWXwo03GFEzjsUm8Q7RZcHPHksttq7/GFoxjCVUjkjvPdw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
-
@phenomlab Thank you!
Looks like @baris is looking at this thread as well. I'm interested to see what he's going to say about this.
-
NodeBB already loads jquery so you don't need to load it from a CDN, if you want to use jquery in a html widget you need to wait for it to load. Here is a sample from nodebb-widget-essentials. https://github.com/NodeBB/nodebb-widget-essentials/blob/master/public/templates/widgets/activeusers.tpl#L39-L43
<script type="text/javascript"> (function() { function myWidgetCode() { $('#someElement').text('jquery should work here!'); } if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', myWidgetCode); } else { myWidgetCode(); } })(); </script>
-
@baris said in Loading JS/JQuery in Extend > Widgets:
<script type="text/javascript">
(function() {
function myWidgetCode() {
$('#someElement').text('jquery should work here!');
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', myWidgetCode);
} else {
myWidgetCode();
}
})();
</script>I just tried and it works perfectly! Thank you!
-