Reputation: 1600
I'm using CodeIgniter
and I've actually created a template.php
file which have the following structure:
<!DOCTYPE html>
<html lang="en">
<?php $this->view('partials/header') ?>
<body class="<?= !isset($backend) ? 'off-canvas-sidebar' : '' ?>">
<div class="wrapper ">
<div class="<?= isset($backend) ? 'main-panel' : '' ?>">
<div class="content">
<?php $this->view($content) ?>
</div>
<?php $this->view('partials/footer') ?>
</div>
</div>
<!-- Core JS -->
<script src="<?= asset_url('assets/js/vendor/core/jquery/jquery.min.js'); ?>"></script>
<?php
//Load dynamic scripts
if(isset($scripts))
{
foreach($scripts as $script)
{
echo '<script src="'. asset_url($script). '"></script>';
}
}
?>
</body>
</html>
essentially when I need to load a view
I write in the controller:
$view['content'] = 'auth/login';
$view['scripts'] = ['assets/js/general/auth.js'];
$this->load->view('partials/template', $view);
where content
is the path of the view
to load inside the template
and scripts
contains all the javascript files which must be loaded.
The problem is that inside the login.php
file, I have:
<script>
$(document).ready(function() {
setTimeout(function() {
$('.card').removeClass('card-hidden');
}, 400);
});
Auth.initialize(true);
</script>
and this code is executed before the page load, so actually I have this loading execution:
the auth.js
is loaded after the step 2, so I will get an error like:
ReferenceError: $ is not defined
that is because these script are loaded after.
For fix the problem I could add the script in the header but I don't want to do that.
Is there a way to fix this?
Upvotes: 0
Views: 254
Reputation: 3502
You can rather use the load callback
function require(url, callback) {
var e = document.createElement("script");
e.src = url;
e.type = "text/javascript";
e.addEventListener('load', callback);
document.getElementsByTagName("head")[0].appendChild(e);
}
require("https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js", function() {
$(document).ready(function() {
setTimeout(function() {
$('.card').removeClass('card-hidden');
}, 400);
});
console.log('loaded');
});
Upvotes: 1