I'm working on a website that includes some JS code that I do not control. That code uses RequireJS to load dependencies and all.
Disclaimer: I'm a RequireJS noob. I understand the basics, but that's pretty much it...
In my website, I need to use VideoJS. VideoJS can work with, or without RequireJS but from what I understand, if RequireJS is used somewhere in the page, I cannot use VideoJS without it.
So I'm loading VideoJS with RequireJS like this:
var MyRequire = requirejs.config({
baseUrl: '/_/js',
paths: {
videojs: 'http://vjs.zencdn.net/5.3.0/video'
}
});
MyRequire(["videojs"], function(videojs) {
videojs('myPlayer', {}, function(){
console.log('...');
});
});
And it's working.
But I want to use a VideoJS plugin to manage preroll ads. (https://github.com/dirkjanm/videojs-preroll)
I tried to include the plugin script with RequireJS, the script is included but as soon as the plugin tries to access the videojs object, I get an error telling me that videojs is not defined.
My guess is that when I load VideoJS as a RequireJS module, it's not in the global scope and the plugin that I'm using is looking for VideoJS in the global scope and that's why I get that error.
Is there any way I can use VideoJS without loading it as a RequireJS module? Or how can I help the plugin find the VideoJS object?
Thanks for your help!
You should use shim from requirejs and inject videojs into global scope. I made an example of code for your case. I tested it and it works (you can see images below):
Loading order:
Requirejs analysis order:
app.js
requirejs.config({
paths: {
"videojs": "./libs/video",
"ads": "./libs/videojs.ads",
"preroll": "./libs/videojs-preroll"
},
shim:{
"preroll": {
deps: ['ads']
},
"ads": {
deps: ["add-video-js-in-global-scope"],
}
}
});
define("add-video-js-in-global-scope",["videojs"], function(videojs) {
window.videojs = videojs;
});
requirejs(["preroll", "ads"], function (preroll,ads) {
// preroll and ads will be undefined because it's not amd.
videojs('idOne', {}, function () {
var player = this;
player.ads(); // initialize the ad framework
// your custom ad integration code
});
});
index.html
<html>
<head>
</head>
<body>
<script data-main="app.js" src="//cdnjs.cloudflare.com/ajax/libs/require.js/2.1.22/require.js"></script>
<div id="idOne"></div>
</body>
</html>
result:
files:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With