My customer has many pages with <script>
elements including javascript.
<script src="https://wordpress.stackexchange.com/questions/82668/myscriptforthispageonly.js"></script>
I’m trying to get all scripts to load in the footer using wp_enqueue_script()
, but I’m not sure how to enqueue a script from within a page.
Again, this is within a WordPress page. Is it possible to enqueue an external script from a page or post?
If that’s not possible, is it possible to delay loading the script until the onload event fires?
General answer: you can call wp_enqueue_script()
directly inline in the template, as of WordPress 3.4 (IIRC).
So, if you have:
<script src="https://wordpress.stackexchange.com/questions/82668/myscriptforthispageonly.js"></script>
You could replace it with:
<?php wp_enqueue_script( 'this-page-script', get_template_directory_uri() . '/myscriptforthispageonly.js', array( 'jquery' ), null, true ); ?>
Edit
From this comment:
This is from within a page. As in a WordPress page. No templates. Imagine you are writing a WordPress blog post update, you switch to HTML vie
Your best course of action would be to define a shortcode for the user to put into the post content, instead of putting a <script>
call itself directly in the post content. Then, in your shortcode callback, you can call wp_enqueue_script()
.