I currently have the problem that I can't manage to import a JS library in wordpress. It is the jsPDF library and in wordpress it throws this error message when I press a button. ReferenceError: Can't find variable: jsPDF
I added this line in functions.php, and also tried it locally.
wp_enqueue_script( 'jsPDF', get_stylesheet_directory_uri() . 'https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.3.0/jspdf.es.js', array( 'jquery' ),'',true );
wp_enqueue_script( 'jsPDF', get_stylesheet_directory_uri() . '/scripts/jsPDF.js', array( 'jquery' ),'',true );
All other custom scripts I use are working. This is the script by using jsPDF. The script is loaded, I can tell by the console.log before the function.
console.log("generate PDF loaded");
function testPDF(){
console.log("testPDF-function works")
var doc = new jsPDF('p', 'pt', 'a4');
doc.fromHTML($('#a4').get(0), 20,20, {
'width':500
});
doc.save('Test.pdf');
}
There are two problems in the way you enqueue your scripts.
So your code should look like:
wp_enqueue_script( 'jsPDF', 'https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.3.0/jspdf.es.js', array( 'jquery' ),'',true );
wp_enqueue_script( 'myJsPDF', get_stylesheet_directory_uri() . '/scripts/jsPDF.js', array( 'jquery' ),'',true );
In your first wp_enqueue_script you had the get_stylesheet_directory_uri()
, so it was looking for a file inside of your theme folder. But it needs to be only the URL of the CDN.
In The second wp_enqueue_script you give it a unique name, so there will be no conflicts. Maybe have another look at https://developer.wordpress.org/reference/functions/wp_enqueue_script/